Modelesq
Modelesq

Reputation: 5402

Account for null values when mapping an array ES6

This is I'm mapping an array successfully..

const faculty = props.faculty;

{(faculty.science_department || []).map(science_dep => (
    <div className="row">
        <p>{science_dep.name} : {science_dep.start_date}</p>
    </div>
))}

But what if the array is empty? How can I account for null values/empty states? How can I check within this map function? Ie: show

<p>There are no faculty members within this category</p>

Upvotes: 0

Views: 110

Answers (3)

Aaron Beall
Aaron Beall

Reputation: 52143

But what if the array is empty? How can I account for null values/empty states? How can I check within this map function? Ie: show

<p>There are no faculty members within this category</p>

Given those requirements I would first filter the array, then render it with the map if it contains anything, otherwise render the placeholder message:

const {faculty} = this.props;
const science_department = (faculty.science_department || []).filter(dep => !!dep);

{ 
    science_department.length ? science_department.map(science_dep => (
        <div className="row" key={warning.id}>
            <p>{science_dep.name} : {science_dep.start_date}</p>
        </div>)
    : 
        <p>There are no faculty members within this category</p> 
}

PS: What is warning.id? The key should be a field of the science_dep with a unique value.

Upvotes: 1

morels
morels

Reputation: 2105

{(faculty.science_department || []).length ? faculty.science_department.map(science_dep => (
<div className="row" key={warning.id}>
    <p>{science_dep.name} : {science_dep.start_date}</p>
</div>
)) : (science_dep => (
<div className="row" key={warning.id}>
    <p>There are no faculty members within this category</p>
</div>)()}

Upvotes: 0

Yuya
Yuya

Reputation: 2311

Assuming you want to do this within JSX syntax, then you can use the ternary operator:

const faculty = props.faculty;

{
  faculty.science_department.length !== 0 ?    
    faculty.science_department.map(science_dep => (
      <div className="row" key={warning.id}>
        <p>{science_dep.name} : {science_dep.start_date}</p>
      </div>
    ))
  :
    <p>There are no faculty members within this category</p>
}

Upvotes: 1

Related Questions