Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle null values in ReactJS?

I'm accessing an API with ReactJS. What is the best way to stop React Component crashing when it's accessing a property in the object provided by the API that may be 'undefined'?

An example of an error is:

TypeError: Cannot read property 'items' of undefined

like image 211
Nathan Horrigan Avatar asked Jun 13 '17 20:06

Nathan Horrigan


People also ask

How do you handle null values in React?

To check for null in React, use a comparison to check if the value is equal or is not equal to null , e.g. if (myValue === null) {} or if (myValue !== null) {} . If the condition is met, the if block will run.

Can you render null in React?

Yes you can, but instead of blank, simply return null if you don't want to render anything from component, like this: return (null); Another important point is, inside JSX if you are rendering element conditionally, then in case of condition=false , you can return any of these values false, null, undefined, true .

Can JSX return null?

If you return null from a component, nothing is rendered. You can also return null to render nothing from a JSX expression.

How do you check for null and undefined in Reactjs?

To check if a variable is null or undefined in React, use the || (or) operator to check if either of the two conditions is met. When used with two boolean values the || operator returns true if either of the conditions evaluate to true .


2 Answers

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

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

}
  • in JSX you do it in this way.

render(){
return(
          <div>
          (typeof x !=='undefined' && typeof x.item !=='undefined')?
                <div>success</div>:           
                <div>fail</div>
          </div>
          )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
like image 28
Rajat Gupta Avatar answered Sep 18 '22 18:09

Rajat Gupta


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)
like image 65
Kenny Meyer Avatar answered Sep 21 '22 18:09

Kenny Meyer