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>}
asked Aug 14, 2019 at 8:43
1

5 Answers 5

2

You can use length property

 {this.props.items.length == 0 ? errorMessage : <h1>Working</h1>}
answered Aug 14, 2019 at 8:45

1 Comment

@Martin hah for you i can replace to "up arrow"
1

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

answered Aug 14, 2019 at 8:45

Comments

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}
answered Aug 14, 2019 at 8:49

Comments

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>}

answered Aug 14, 2019 at 8:50

Comments

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> }
answered Aug 14, 2019 at 8:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.