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>}
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>}
You can use length
property
{this.props.items.length == 0 ? errorMessage : <h1>Working</h1>}
this.props.items && this.props.items.length > 0 ? <h1>Working</h1> : errorMessage
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}
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>}
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> }