简体   繁体   中英

How to loop a react conditional rendering statement

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"
        }
    ],

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 }

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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM