Search code examples
javascriptreactjsecmascript-6create-react-app

Import images from another file in React


I am using create-react-app to build a simple web page:

index.js:

import lostImage from './assets/img/illustrations/lost.svg';

function Image(props) {
    return (
        <img src={lostImage} />
    );
}

It works as expected, however I plan to import dozens of images, so I decided to move the import calls in a separate file in the same directory:

images.js:

import lostImage from './assets/img/illustrations/lost.svg';

index.js:

import './images.js';

function Image(props) {
    return (
        <img src={lostImage} />
    );
}

However I get the lostImage not defined error. How do I properly do this?


Solution

  • You need to export them from images.js file. Then import them to the index.js file to use.

    images.js:

    import lostImage from './assets/img/illustrations/lost.svg';
    export { lostImage };
    

    index.js:

    import {lostImage} from './images.js';
    
    function Image(props) {
        return (
            <img src={lostImage} />
        );
    }