Jack The Baker
Jack The Baker

Reputation: 1883

ReactJS check value in map

I want to check v.name if exist:

{value.district && value.district.length > 0 ? value.district.map((v,i) => 
    <span key={i}>{v.name} </span>
) : 'Nothing'}

This json:

{
   "current_page":1,
   "data":[
      {
         "id":9,
         "hash":"X3JTgxOQlWk0ZIMBVe41",
         "province":{
            "id":1,
            "name":"yyyy"
         },
         "city":{
            "id":3,
            "name":"xxx"
         },
         "district":[
            {
               "id":107,
               "name":"blah blah"
            }
         ]
      },
      {
         "id":10,
         "hash":"IObmLaVewiNf9cn1ETQy",
         "province":{
            "id":2,
            "name":"zzzzzzzzzzz"
         },
         "city":{
            "id":4,
            "name":"rrrrrrrrrrrrrr"
         },
         "district":[
            null
         ]
      }
   ]
}

Error:

Cannot read property 'name' of null

I tried:

{v.name ? v.name : null}

But still got error. how can I do this?

Upvotes: 1

Views: 46

Answers (2)

Robin Zigmond
Robin Zigmond

Reputation: 18249

Two possible solutions:

You can replace {v.name} with a guard to check that v is not null, which could be either of:

  • {v && v.name}

  • {v ? v.name : null} (which is very close to what you tried, but please note the difference - v.name throws the error when v is null so you can't use that to check)

Or filter the array before map-ing it:

{value.district && value.district.length > 0 ? value.district.filter(v => v).map((v,i) =>
    <span key={i}>{v.name} </span>
) : 'Nothing'}

the additional .filter(v => v) simply removes any falsy values, such as null.

Upvotes: 1

adel
adel

Reputation: 3507

to solve this check if the item in array is valid or not null like this:

 {value.district && value.district.length > 0 ? value.district.map((v,i) => 
 (v?<span key={i}>{v.name} </span>:null)): 'Nothing'}

Upvotes: 2

Related Questions