Nandra Mihnea
Nandra Mihnea

Reputation: 31

How to display images dynamically in React based on the respose from the server

I am calling the OpenWeatherMap API and getting in the response the icon id 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 icon id 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: props.icon == '01d' => display image 01d.png


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} alt={props.icon}/>
        </div>
    )
}

export default current;

Upvotes: 0

Views: 131

Answers (1)

Kevin.a
Kevin.a

Reputation: 4296

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`} alt={props.icon}/>
        </div>
    )
}

export default current;

Instead of using + operator to concatenate strings, you can use the handy template literal to make it a lot easier for you to concatenate strings together. Also add the .png format to the end of your file path since its an image you specify the extension name

Upvotes: 1

Related Questions