Home > Mobile >  Cannot get the first element of array whereas map() works as a charm
Cannot get the first element of array whereas map() works as a charm

Time:01-20

In a React component want to print out the a value of an object ("name") which is the first element in the array:

"production_countries": [
  {
    "iso_3166_1": "US",
    "name": "United States of America"
  }
]

This code collapses the app with error TypeError: Cannot read properties of undefined (reading 'name'):

<p>
  {
    movie.production_countries &&
    movie.production_countries[0].name
  }
</p>

However, if I replace the code above with a .map() everything works as a charm.

<p>
  {movie.production_countries &&
    movie.production_countries?.map((country, i) => (
      <span key={i}>
        {country.name}
      </span>
    ))}
</p>

How can I get the first element of array? Thanks

CodePudding user response:

production_countries could be an empty array, in which case [0] will return undefined, using ? for early return should work:

{
  movie.production_countries &&
  movie.production_countries[0]?.name
}
  •  Tags:  
  • Related