0

I'm passing an array from an API and want to know if the array is empty, to print an error message.

Look at different sites and none of them were working.

      {this.props.items ? errorMessage : <h1>Working</h1>}
Jonathan
  • 459
  • 1
  • 4
  • 18
  • 3
    Possible duplicate of [How can I check whether an array is null / empty?](https://stackoverflow.com/questions/2369967/how-can-i-check-whether-an-array-is-null-empty) – Avinash Aug 14 '19 at 08:48

5 Answers5

2

You can use length property

  {this.props.items.length == 0 ? errorMessage : <h1>Working</h1>}
Idan
  • 2,556
  • 21
  • 31
1

this.props.items && this.props.items.length > 0 ? <h1>Working</h1> : errorMessage

Mukesh Soni
  • 6,498
  • 3
  • 27
  • 35
1

Fist check weather Array exists or not then check the length of Array greater than 0, always use double negations to convert that array into bool type

{!!this.props.items && this.props.items.length > 0 ? <h1>Working</h1> : errorMessage}
Harsh kurra
  • 964
  • 1
  • 8
  • 19
1

Check the lodash library. It's very helpful for that kind of needs.

https://lodash.com/docs/4.17.15#isEmpty

With this you could just use:

{isEmpty(this.props.items) ? errorMessage: <h1>Working</h1>}

pawelbylina
  • 1,207
  • 10
  • 15
0

Safer to check with the type before checking its length, as type string can return length as well

{ Array.isArray(this.props.items) && this.props.items.length < 1 ? errorMessage : <h1>Working</h1> }
Jee Mok
  • 5,433
  • 8
  • 44
  • 70