Load local images in React.js

Atul picture Atul · May 24, 2017 · Viewed 103.8k times · Source

I have installed React using create-react-app. It installed fine, but I am trying to load an image in one of my components (Header.js, file path: src/components/common/Header.js) but it's not loading. Here is my code:

import React from 'react'; 

export default () => {
  var logo1 = (
    <img 
      //src="https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-goose.jpg"
      src={'/src/images/logo.png'}
      alt="Canvas Logo"
    />
  );
  return (
    <div id="header-wrap">
      <div className="container clearfix">
        <div id="primary-menu-trigger">
          <i className="icon-reorder"></i>
        </div>
                    
        <div id="logo">
          <a href="/" className="standard-logo" data-dark-logo='/images/logo-dark.png'>{logo1}</a>
          <a href="/" className="retina-logo" data-dark-logo='/images/[email protected]'>
            <img src='/var/www/html/react-demo/src/images/[email protected]' alt="Canvas Logo" />
          </a>
        </div>
      </div>
    </div>
  );
} 

If I write the image path as src={require('./src/images/logo.png')} in my logo1 variable, it gives the error:

Failed to compile.

Error in ./src/Components/common/Header.js

Module not found: ./src/images/logo.png in /var/www/html/wistful/src/Components/common

Please help me solve this. Let me know what I am doing wrong here.

Answer

Dan Abramov picture Dan Abramov · May 24, 2017

If you have questions about creating React App I encourage you to read its User Guide.
It answers this and many other questions you may have.

Specifically, to include a local image you have two options:

  1. Use imports:

    // Assuming logo.png is in the same folder as JS file
    import logo from './logo.png';
    
    // ...later
    <img src={logo} alt="logo" />
    

This approach is great because all assets are handled by the build system and will get filenames with hashes in the production build. You’ll also get an error if the file is moved or deleted.

The downside is it can get cumbersome if you have hundreds of images because you can’t have arbitrary import paths.

  1. Use the public folder:

    // Assuming logo.png is in public/ folder of your project
    <img src={process.env.PUBLIC_URL + '/logo.png'} alt="logo" />
    

This approach is generally not recommended, but it is great if you have hundreds of images and importing them one by one is too much hassle. The downside is that you have to think about cache busting and watch out for moved or deleted files yourself.

Hope this helps!