I want to make a web with the subject of weather. I got to the point in the construction process that the icon should change with the change of weather.
let shiftIcon = () => {
let icon = "";
let iconText = data.date[0].weather.code;
if (iconText == 600) {
icon = "https://img.icons8.com/external-those-icons-lineal-color-those-icons/48/000000/external-wind-weather-those-icons-lineal-color-those-icons.png";
return (
<img src={icon} />
);
} else {
return null;
}
}
<div className="col col-3">
{shiftIcon()}
</div>
And after writing this code, I got an error. Do you have a solution for this?
TypeError: Cannot read properties of undefined (reading '0') shiftIcon E:/Projects and trainings/Education Courses/react.js courses/Person/weather-application/src/components/boxNew.js:32 29 | let shiftIcon = () => { 30 | 31 | let icon = ""
32 | let iconText = data.date[0].weather.code; | ^ 33 | 34 | if (iconText == 600) { 35 | icon = "https://img.icons8.com/external-those-icons-lineal-color-those-icons/48/000000/external-wind-weather-those-icons-lineal-color-those-icons.png";
CodePudding user response:
Initially data is undefined. You should use optional chaining to get rid of the runtime exceptions.
Try like this
let iconText = data?.date?.[0]?.weather?.code;
