Modelesq
Modelesq

Reputation: 5402

If conditional check in react jsx for empty values [es6]

I have an array

const myArray = this.props.values.students;

How can I display none if the array is empty?

This is what I'm currently using...

<p>{this.props.values.students ? myArray : 'None' }</p>

It doesn't seem to render 'None' if the array is in-fact empty. How can I make this work?

Upvotes: 1

Views: 11178

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47127

The problem is that an empty array is not a falsy value:

if ([]) {
  console.log('truly - this will happen');
}
else {
  console.log('false - this will *never* happen');
}

You can however check the length of the array, which will give a falsy value when empty (0)

<p>{this.props.values.students.length ? myArray : 'None' }</p>

Upvotes: 10

Related Questions