6

I am looping through an array of objects in react using array.map. The array takes the form:

const seasons = [
             {air_date: null, episode_count: 6},
             {air_date: "2020-02-02", episode_count: 6}
           ]

I am looping through the array using seasons.map, returning JSX if air_date is not null and null otherwise.

 seasons.map((season, index) => {
      if(season.air_date){
         return <span key = {season.id}> {season.episode_count} </span>
     }else{
        return null; // Is this recommended?
    }  
})

I have never seen anyone do this (returning null instead of JSX). Is it recommended in react? I don't want to use a for loop.

3
  • How come you didn't see that? It's the most common way to map an array in jsx. Commented Jul 25, 2020 at 13:04
  • I have ever seen map being used to loop through arrays. What i have never seen is null being returned instead of JSX. Commented Jul 25, 2020 at 13:08
  • 1
    Because there are other options. Probably this is why you don't see something like this. A logical && is necessary for your needs for example. You don't even need to use an if/else statement like that. Commented Jul 25, 2020 at 13:14

2 Answers 2

10

Yes, this is recommended.

If you have a conditional or optional component then returning null to mean "no component" or "no JSX" is the way to go.

In addition, as @k-wasilweski says, using a .map to convert an array into a series of components is standard practice in React.

If you don't like the idea of returning nulls, you could always add a .filter(c => c !== null) at the end, but it's really unnecessary.

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

Comments

3

Thats quite okay, but in React its more common to do it using the ternary operator:

seasons.map((season, index) =>
  season.air_date ? <span key={season.id}> {season.episode_count} </span> : null
);

And like @devserkan mentioned in the comment below, you can even just do:

seasons.map((season, index) =>
  season.air_date && <span key={season.id}> {season.episode_count} </span>
);

4 Comments

Not even a ternary is needed here. && also works fine.
true I added your suggestion to the comment.
Thanks for the feedback. I know about && and ternary operator. I chose if else because of the many lines of JSX i am returning. Use of if elsein this case makes the code more readable compared to && and ternary operator. The example is a simplified version of what i was trying to do.
no, thats not what I mean't, the span should only render when season.air_date is not null

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.