String not outputting in a foreach loop

Viewed 28

I am new to react and I am trying to create a foreach loop. However when its outputted in the browser it shows like this

[object Object][object Object][object Object]

Not sure why its happening

Below is my code any help would be really appreciated. Thanks!

const Book =({book_info})=> {



    let output = "";


    book_info.forEach(book => {
        //console.log(book.title);

        output += <h1> {book.title}</h1>

    });

    console.log(output);
    return <section>

        {output}
    </section>

};

const Library = () => {
    let book_info = [{title:"The sun also rises", author:"Ernest Hemigway",pages: 260},{title:"The sun also rises", author:"Ernest Hemigway",pages: 260},{title:"The sun also rises", author:"Ernest Hemigway",pages: 260}];
    return (

        <div>
           <Book book_info={book_info}/>
        </div>
    )
};
1 Answers

The problem is with this line:

output += <h1> {book.title}</h1>

It is effectively looping through book_info and converting the h1 react component to a string which is [object Object].

What you want to do is:

return <section>
  {book_info.map(book => <h1>{book.title}</h1>)}
</section>

This loops through book_info and maps the react element as children to the <section> element.

Related