Home > Software engineering >  Unsure why receiving " Objects are not valid as a React child " error
Unsure why receiving " Objects are not valid as a React child " error

Time:10-29

react-dom.development.js:14887 Uncaught Error: Objects are not valid as a React child (found: object with keys {name, img, author, price}). If you meant to render a collection of children, use an array instead.

import React from "react";
const books = [
  {
    name: "The Psychology of Money",
    img: "https://m.media-amazon.com/images/I/71g2ednj0JL._AC_UY218_.jpg",
    author: "morgan hussel",
    price: "239",
  },
  {
    name: "The Psychology of Money",
    img: "https://m.media-amazon.com/images/I/71g2ednj0JL._AC_UY218_.jpg",
    author: "morgan hussel",
    price: "239",
  },
];


function BookList() {
  return <div>
    <h1>{books.map((book) => {return book})}</h1>
  </div>;
};

export default BookList;

CodePudding user response:

React doesn't render objects and in return book, since book is an object, you are returning objects.

What you want instead is return a string (e.g., return book.name) or wrap the object properties in elements and return those (e.g., return <h1>book.name</h1>).

Example:

function BookList() {
  return <div>
    <h1>{books.map((book) => {return book.name}</h1>
    <hr />
    {books.map((book) => {
      return (
        <div>
          <h1>{book.name}</h1>
          <div>{book.author} - ${book.price}</div>
          <img src={book.img} />
          <hr />
        </div>
      )
    })}
  </div>;
};

Demo:

const books = [
  {
    name: "The Psychology of Money",
    img: "https://m.media-amazon.com/images/I/71g2ednj0JL._AC_UY218_.jpg",
    author: "morgan hussel",
    price: "239",
  },
  {
    name: "The Psychology of Money",
    img: "https://m.media-amazon.com/images/I/71g2ednj0JL._AC_UY218_.jpg",
    author: "morgan hussel",
    price: "239",
  },
];


function BookList() {
  return <div>
    Elements:<br />
    {books.map((book) => {
      return (
        <div>
          <h1>{book.name}</h1>
          <div>{book.author} - ${book.price}</div>
          <img src={book.img} />
          <hr />
        </div>
      )
    })}
    <hr />
    Or just strings:<br />
    <h1>{books.map((book) => {return book.name})}</h1>
  </div>;
};


ReactDOM.createRoot(document.getElementById('app')).render(<BookList />);
<script type="text/javascript" src="//unpkg.com/react@18/umd/react.production.min.js"></script>
<script type="text/javascript" src="//unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>

<div id="app"></div>

CodePudding user response:

You can't render objects if you want to access the array of objects then you can do this.

<h1>
{
  books.map((book) => {
    return <div> {book.name} </div>
    })
 }
</h1>
  • Related