Reputation: 21
I am making a seven day forecast react app. I have an images folder that has 28 icons for weather types split between day and night versions. Those images are imported like so into a component (for brevity I will only show 4 options):
import {
dayclear, daycloudy,
nightclear, nightcloudy
} from '../images'
Depending on the type of weather when this component is called, I'm trying to dynamically name an image source. Is there a way to concatenate a object name dynamically? Ex:
<img src={this.props.timeOfDay + this.props.weather} alt="Weather Image" />
I'm looking for that source to end up being the object name of the imported image.
Upvotes: 2
Views: 53
Reputation: 1047
Yeah, there is a way.
First, write the import statement like this.
import * as WeatherIcons from '../images'
Then add the image to the src
attribute as mentioned below.
<img src={WeatherIcons[this.props.timeOfDay + this.props.weather]} alt="Weather Image" />
Here I consider that,
timeOfDay
prop can be day or nightweather
prop can be clear or cloudyUpvotes: 1
Reputation: 1143
try to store your images in a object like this:
const IMAGES = {
dayclear,
nightclear,
...
}
then create a weather name with
const { timeOfDay, weather } = this.props
const weatherName = `${timeOfDay > condition ? 'day' : 'night'}${weather}`
finally add it to src of image:
<img src={IMAGES[weatherName]} alt="Weather Image" />
Upvotes: 3