0

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0
{(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>)()}

2 Comments

Seems to throw an unexpected token error regarding </div>)()}
do you want to assign the "<div> ..." to a variable or attach it to a dom element ?

Your Answer

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.