0

I want to render Object "genres" but my console returns to me :

Error: Objects are not valid as a React child (found: object with keys {genre}). 
If you meant to render a collection of children, use an array instead.

My code

function Movie({title,summary,year,poster,genres}){ 
    return(
        <div className="movie">
            {genres.map(genre=>{return {genre}})} //doesn't work
        {genres.map(genre=>{return <li>{genre}</li>})}
         </div>
    )
}

the first code

{genres.map(genre=>{returns {genre}})}

doesn't work

But the second code below works well.

{genres.map(genre=>{returns <li>{genre}</li>})} 

What's the difference between these two things?

3
  • This article explains it in details akashmittal.com/react-error-objects-not-valid-react-child Commented Dec 16, 2020 at 12:11
  • First one is returning an array of objects ({ genre } creates an object using shorthand property name) . The second one is returning an array of <li> Commented Dec 16, 2020 at 12:11
  • <div className="movie">{ genres.join(" ") }</div> Commented Dec 16, 2020 at 12:17

2 Answers 2

1

This line

{genres.map(genre=>{returns {genre}})}

returns an object, out of each item in the array: { genre: 'drama' }

However, this other line

{genres.map(genre=>{returns <li>{genre}</li>})} 

The { inside the JSX for li won't turn it into an Object, but will access its value: <li>drama</li>

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

Comments

0

The first code returns an object with key "genre" which its value is the genere value, and react can't render it.

The second one return the value of genre, because the braces here aren't an object braces but the correct syntax of putting variables inside html in react.

If you want to return the value without li, do: {genres.map(genre=> genre)}

2 Comments

This expression returns array of undefineds though. genres.map(genre=>{return {genre}})
It was really helpful for me.Thanks a lot

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.