Search code examples
reactjscomponentsconditional-statementsrendering

Conditional Reading in react working but shouldn't?


So the question is, this code works perfectly but why when I remove the return(Header /) it doesn't work but it returns the correct Header type when return(Header /) is there depending on what the props.weather is?

Surely it should return and not any others if its depending on it?

also if anyone can re-format this any better feel free, relatively new to it.

import Header from './header'
import HeaderCloudy from './headercloudy'
import HeaderSunny from './headerSunny'
import HeaderRaining from './headerRain'

function HeaderLoadOut(props){
//log weather from api by city
console.log(props.weather);
//convert
  let types = {
    weather: props.weather
  }
//check weather load weather

if (types.weather == 'Clouds'){
  return <HeaderCloudy />
} else if (types.weather == 'Sunny'){
  return <HeaderSunny />
} else if (types.weather == 'Clear'){
  return <HeaderSunny />
} else if (types.weather == 'Rain'){
  return <HeaderRaining />
} else if (types.weather == 'Snow'){
  return <HeaderRaining />
}

console.log(types.weather)
return (
  <Header />
)

}
export default HeaderLoadOut;


Solution

  • Try using an object to map your weather type, also, in functional component you must render a react element, therefore you must supply a node like Header or any value as specified in docs.

    const WEATHER_TYPE = {
      Clouds: <HeaderCloudy />,
      Sunny: <HeaderSunny />,
      Clear: <HeaderSunny />,
      Rain: <HeaderRaining />,
      Snow: <HeaderRaining />
    };
    
    function HeaderLoadOut({ weather }) {
      return weather ? WEATHER_TYPE[weather] : <Header />;
    }
    
    export default HeaderLoadOut;
    

    As stated in docs, undefined is also a valid react element:

    function HeaderLoadOut({ weather }) {
      return WEATHER_TYPE[weather];
    }