Error: Objects are not valid as a React child in ReactJs
Dung Do Tien May 15 2022 477
I have a small app to help manage the books store. I use Reactjs to help raw a list of books. Like this:
import * as React from "react";
export default function App() {
const lstBooos = [{ 0: "pro reactjs", 1: "Rose", 2: 5000 }, { 0: "pro javascript", 1: "Rose 2", 2: 7000 }]; // list data will get from API
const render = lstBooos.map((item) => {
return <p> {item}</p>;
});
return <div>{render}</div>;
}
When running the project I got an exception Objects are not valid as a React child (found: object with keys {0, 1, 2}). If you meant to render a collection of children, use an array instead.
Anyone can help me explain this error?
Thanks in advance.
Have 1 answer(s) found.
- J1
Javier May 15 2022
I think you have a format problem with your list data. You need to remember that you can not use objects in JSX. I suggest you 2 solutions:
Solution 1: use format
["data1", "data2"]
instead of{0: "data1", 1: "data2"}
import React from 'react'; export function App(props) { const lstBooos = [["pro reactjs", "Rose", 5000], ["pro javascript", "Rose 2", 7000]]; const render = lstBooos.map((item) => { return <p> {item}</p>; }); return ( <h1>{render}</h1> ); }
Solution 2: use format
{key: value, key: value}
instead of{0: "data1", 1: "data2"}
import React from 'react'; export function App(props) { const lstBooos = [{Name:"pro reactjs", Author: "Rose", Price: 5000}, {Name: "pro javascript", Author: "Rose 2", Price:7000}]; const render = lstBooos.map((item) => { return <p> {item.Name}, {item.Author}, {item.Price}</p>; }); return ( <h1>{render}</h1> ); }
I prefer solution 2 more.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.