Nandra Mihnea
Nandra Mihnea

Reputation: 31

Proper way to load local stored images from folder in React

I am calling the OpenWeatherMap API and getting in the response the iconID like 01d or 04n. I've set up all the images under a local directory in /src and named them 01d.png, 04n.png etc.

I've passed this iconID via props to my Current.js component and I don't know how can I display the image with the specific id name.

E.G:

I would like to display image 01d.png if the response from the server is equal to 01d

P.S:

props.icon stores the data from the server and it is indeed good data.

import React from 'react';
import classes from './Current.module.css';

const current = (props) => {
    return (
        <div className={classes.Current}>
            <p>Temperature: {props.temperature}</p>
            <p>Minimum Temperature: {props.minimumTemperature}</p>
            <p>Maximum Temperature: {props.maximumTemperature}</p>
            <p>Humidity: {props.humidity}</p>
            <img src={'../../icons/' + props.icon + '.png'}[enter image description here][1] alt={props.icon}/>
        </div>
    )
}

export default current;

Here is a screenshot of my folder structure

Upvotes: 1

Views: 42

Answers (1)

Amir-Mousavi
Amir-Mousavi

Reputation: 4561

First of all make sure that the images folder is not out of src, then load image like

<img src={require(`../../icons/${props.icon}.png`)} />

Or if it is only one image id passed to component and no need for maping you can lazy load it when component renders.

const current = (props) => {
   const pic = React.lazy(()=>import(`../../icons/${props.icon}.png`))
   ......

Then wrap the img tag with Suspense and <img src={pic} />

Upvotes: 2

Related Questions