简体   繁体   中英

How to correctly use switch statement in JSX (react)?

I have a react component that is a weather dashboard. I am trying to display an image for today's weather conditionally. It would be really nice if I could use JSX in an src attribute. Here is an example of what I would like to do...

I import my weather images at the top of my component:

import rain from 'my image path'
import sun from 'my image path'

This is a functional react component. In my component that gets today's weather and sets a state value 'weatherToday' to 'rain', 'sun', etc depending on the weather today. For example:

const [weatherToday, setweatherToday] = useState('rain');

Now down in the HTML that I am returning from my component, I have an img tag. In the src attribute of that img tag, can I use JSX? It is not clear if I can or cannot but what I've been trying so far has not worked.

Here is my attempt to do this so far.

      <img src={
      (() => {
            switch(weatherToday === 'rain') {
                case "rain": return rain;
                default: return sun;
              }
            })
      } ></img>

The result is a broken image link. What am I doing incorrectly?

Inside your component function, you should declare and manipulate a variable like below (of course switch statement can also be used to achieve below):

 let weatherImg = "";
    // and conditionally update it as required like below -
    if(weatherToday == rain) {
    weatherImg = "whatever image name you imported from image path"
    } else if (condition 2) {
    weatherImg = "path 2"
    } else if (condition 3) {
    weatherImg = "path 3"
    } else {
    weatherImg = "whatever default image you want to show"
    }

Then you pass the value of weatherImg variable to src attribute in image tag.

 <img src={weatherImg}></img>

An advantage of writing this way is, someone reading this code can take a quick glance at it, as it will be at the top of your JSX code and determine the conditions that are causing the image to change. So in future if any change is needed it is easy to make unlike the case that you have shown which frankly speaking I haven't tried and it looks harder to read and has mistakes as pointed in comments section.

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