minami
minami

Reputation: 237

Render object in React

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?

Upvotes: 0

Views: 293

Answers (2)

Christopher Francisco
Christopher Francisco

Reputation: 16268

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>

Upvotes: 1

fullstack
fullstack

Reputation: 834

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

Upvotes: 0

Related Questions