0

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;
2
  • You're missing .png Commented Nov 21, 2019 at 19:07
  • Unfortunately this wasn't the case. I've actually forgot to add the + '.png' when I copied the code from VS Code. Thanks for the suggestion anyways :) Commented Nov 23, 2019 at 15:43

1 Answer 1

1
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

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

1 Comment

I've tried as you suggested and even deleted the apostrophe inside the backticks and the results were the same. Maybe I need to import them somewhere? Because when I do 'import icon from blablabla' and use it like src={icon} it displays correctly. Any suggestions?

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.