nibble
nibble

Reputation: 404

Returning null instead of a JSX when looping through arrays in react using map

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.

Upvotes: 6

Views: 4425

Answers (2)

Talmacel Marian Silviu
Talmacel Marian Silviu

Reputation: 1736

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>
);

Upvotes: 3

Dancrumb
Dancrumb

Reputation: 27579

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.

Upvotes: 10

Related Questions