I have a problem with React conditional rendering. I want to render a specific prop if it's set so first I'm checking if the prop exists and then outputing it otherwise output 0, but React has a problem checking if the variable exists when it's undefined at first load...
number:
props.dashboardCards[0].items.thisMonth[0].itemTitle
? props.dashboardCards[0].items.thisMonth[0].itemTitle
: 0,
This is my code I want to create an object with number field and in that field I want to set this prop if it exists otherwise 0. And React keeps giving me error:
TypeError: Cannot read properties of undefined (reading 'itemTitle')
thisMonth is probably empty or undefined. You can use optional chaining to solve this:
number: props.dashboardCards[0]?.items?.thisMonth[0]?.itemTitle ?? 0,
Now if props.dashboardCards[0].items.thisMonth[0].itemTitle exists number will be the value of it, or it'll be 0.
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
Learn more about optional chaining from here.
The error says that there is no itemTitle in the thisMonth array.
If it's coming from the API, you need to wait to get it. You can simply check the props by the console.log(props) and check it before using dot notation to get the itemTitle.
You can also check for a value with optional chaining ? :
props?.dashboardCards[0]?.items?.thisMonth[0]?.itemTitle
It means:
if(props){
if(dashboardCards[0]){
if(items){
if(thisMonth[0]){
props.dashboardCards[0].items.thisMonth[0].itemTitle
}
}
}
}