admin管理员组

文章数量:1287119

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?

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?

Share Improve this question asked May 16, 2016 at 16:18 ModelesqModelesq 5,40220 gold badges63 silver badges89 bronze badges 1
  • 2 Check the length of the array? {this.props.values.students.length ? ... : 'None'} – Andreas Louv Commented May 16, 2016 at 16:21
Add a ment  | 

1 Answer 1

Reset to default 10

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>

本文标签: javascriptIf conditional check in react jsx for empty values es6Stack Overflow