Best way to handle null values in ReactJS? Best way to handle null values in ReactJS? reactjs reactjs

Best way to handle null values in ReactJS?


It looks like you're trying to access the property items of a variable x.

And if x is undefined, then calling x.items will give you the error you mentioned.

Doing a simple:

if (x) {  // CODE here}

or

if (x && x.items) { // ensures both x and x.items are not undefined  // CODE here}

EDIT:

You can now use Optional Chaining, which looks sweet:

if (x?.items)


  • In simple function you do it simply by if statement.

if(typeof x !=='undefined' && typeof x.item !=='undefined'){}