Dynamically Loading Local Images with ReactJS Dynamically Loading Local Images with ReactJS reactjs reactjs

Dynamically Loading Local Images with ReactJS


You can include the folder of images by creating a new context with require.context(). From there, you can dynamically access the image you want from that folder, and set it as a src.

Going off of a structure like this:

APP├──webpack.config.js├──src     ├──containers        ├──YourContainer.js     ├──components        ├──YourComponent.js├──public     ├──bundle.js     ├──images           ├──dog.png           ├──cat.png

In YourContainer.js, you want to create a new context to require that images directory

const images = require.context('../../public/images', true);

From there, you can reference an image specifically:

const dog = images('./dog.png');

or dynamically:

let animal = images(`./${someVariable}.png`);

For a more full example, here's how you can do it while iterating over an object, using the keys to pull your image, and passing that as a style prop to a child component:

let YourContainer = ({ dispatch }) => {const data = projectData["projectData"];// Require context image folderconst images = require.context('../../public/images', true);return (            <div className="container-fluid">        <Row>            {                // Iterate over data object                Object.keys(data).map((keyname, keyindex)=> {                    let code = data[keyname]["code"];                    let title = data[keyname]["title"];                    // Dynamically reference image                    // Set as inline style                    // Pass as prop to child                    let imgsrc = images(`./${code}.png`);                    let styler = {                        backgroundImage: `url(${imgsrc})`                    }                    return <YourComponent                                 key={keyindex}                                title={title}                                 style={styler}                             />                })            }           </Row>          </div>  )   }


Seeing as this question has not been answered, and i was too searching for the answer,

I came across a nifty trick to load images using just a url

Assuming you are using create-react-app plugin

You can use the public folder to render images dynamically

for example, if you put an image with the name "image.jpg" in the public folder of your react app.

you can load it by doing the following

<img src={`${process.env.PUBLIC_URL}/image.jpg`} />

More information can be found below.https://create-react-app.dev/docs/using-the-public-folder


Mention the image folder path where you have a images. I have created the folder under the 'SRC' folder. So i keep my code like below.

let images = require.context('../../../assets/images', true);let itemImg = images(`./${dynamicObject.photo}`).default;

default is main keyword.