I have a react weather app and when my app fetches the data back from the api, i want it to display a background video depending on the data that gets fetched back. Api from openweathermap.
Basically my logic is " If weather description = to weather description, play description.mp4 video from "assets" folder. Only want to display one video per state in my react app(single page app).
The code works but i'm looking for more efficient solution especially if i want to add more videos depending on the fetched data from the api. I have tried incorporating a loop into it and an array that contains the video descriptions but no luck yet.
Thanks ! this is my first post here.
import rainy from './assets/rainy.mp4';
import clearsky from './assets/clearsky.mp4';
import cloudy from './assets/cloudy.mp4';
import mist from './assets/mist.mp4';
import overcast from './assets/overcast.mp4';
{(data.weather ? data.weather[0].description : null) === 'few clouds' &&
<video autoPlay="autoplay" muted loop>
<source src={cloudy} type="video/mp4"/>
</video>
}
{(data.weather ? data.weather[0].description : null) === 'clear sky' &&
<video autoPlay="autoplay" muted loop>
<source src={clearsky} type="video/mp4"/>
</video>
}
{(data.weather ? data.weather[0].description : null) === 'overcast' &&
<video autoPlay="autoplay" muted loop>
<source src={overcast} type="video/mp4"/>
</video>
}
The below is the json file snippit of the data i want to fetch.
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
],
CodePudding user response:
Here is my answer.
{data.weather &&
data.weather[0].description === 'few clouds' ?
<video autoPlay="autoplay" muted loop>
<source src={cloudy} type="video/mp4"/>
</video>
: null
}
CodePudding user response:
You can simplify your code by defining an helper function returning the src
based on the description
:
const getSource = (description) => {
switch (description) {
case 'few clouds':
return cloudy;
case 'clear sky':
return clearsky;
...
default:
return null;
}
}
{
(data.weather && data.weather.length > 0 && getSource(data.weather[0].description) && (
<video autoPlay='autoplay' muted loop>
<source src={getSource(data.weather[0].description)} type='video/mp4' />
</video>
);
}