Skip to content Skip to sidebar Skip to footer

Check If An Array Is Empty In React Native

How can I check if an array is empty with a IF statment? I have this array 'acessos' that's empty ... constructor(props){ super(props); this.state = { acessos:[]

Solution 1:

I agree to Julien. Also you don't have to compare it to null. You can write it like

this.state.acessos && this.state.acessos.length > 0

Solution 2:

Just check if your array exists and has a length:

if (this.state.products && this.state.products.length) {
     //your code here
}

No need to check this.state.products.length > 0.
0 is falsy anyway, a small performance improvement.


Solution 3:

You need not even check for the length since ECMAScript 5.1 You can simply write the same condition as follows.

this.state.acessos && this.state.acessos.length

By default this.state.acessos.length checks if the length is NOT undefined or null or zero.


Solution 4:

If checking the array length as part of conditional rendering in React JSX, remember that if condition is falsy at length check, it will render a 0 as in the following example:

{myArray && myArray.length && (
      <div className="myclass">
        Hello
      </div>
    )}

This is not what we want most of the time. Instead you can modify the JSX as follows:

{myArray && myArray.length? (
      <div className="myclass">
        Hello
      </div>
    ):""}

Post a Comment for "Check If An Array Is Empty In React Native"