sdvnksv
sdvnksv

Reputation: 9678

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?

Upvotes: 1

Views: 1183

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118299

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} />
    );
}

Upvotes: 1

Related Questions