1

How to import and use images in Reactjs? I have imported all images from a folder but it does't return array with links. check this.

    function importAll(r) {
    return r.keys().map(r);
  }
    const images = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));
    console.log(images);

Check this screenshot of console:

Please help me in this!

Folder structure:

--src>
  --components>
      Projects.jsx
  --img>
       images

I am trying to import it in Projects component. but, How to do this?

import React from 'react';
import '../App.css';

function importAll(r) {
    return r.keys().map(r);
}

const images = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));
console.log(images);

Please help in load the all images and use them.

1 Answer 1

2

the correct require for you would be:

importAll(require.context('./img', false, /\.(png|jpe?g|svg)$/));

From docs:

require.context('./test', false, /\.test\.js$/);
// a context with files from the test directory that can be required with a request endings with `.test.js`.


require.context('../', true, /\.stories\.js$/);
// a context with all files in the parent folder and descending folders ending with `.stories.js`.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, i had not seen the problem with path. I got it now. Also there should be two dot : importAll(require.context('../img', false, /\.(png|jpe?g|svg)$/)); It's working now. Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.