It is necessary to get values from an array of objects and display them on the screen. Now I get an error in the console: Error: Objects are not valid as a React child (found: object with keys {title}). If you meant to render a collection of children, use an array instead. It also says in the console: The above error occurred in the component. How can this problem be solved?
ListItem.js:
const ListItem = (props) => {
return (
<div>
<h2>{props}</h2>
</div>
);
};
export default ListItem;
List.js:
import ListItem from "./ListItem/ListItem";
const listObj = [
{
title: "House 1",
},
{
title: "House 2",
},
{
title: "House 3",
},
];
function HouseList() {
return listObj.map((house, index) => {
return <ListItem key={index} title={house.title} />;
});
}
const List = () => {
return (
<div style={{ width: "50%" }}>
<HouseList />
</div>
);
};
export default List;
CodePudding user response:
you should use {props.title} instead of only props. Here is the codesandbox link
The props would be everything so you should give the absolute object path.
props={title:"React", version:18} so if you call just {props}, you will get {title:"React", version:18} so you should define {props.title} {props.version}
Plus, you can level up your knowledge about props just by reading this React official doc https://reactjs.org/docs/components-and-props.html
const ListItem = (props) => {
return (
<div>
<h2>{props.title}</h2>
</div>
);
};
CodePudding user response:
Simply we can use :-
JSON.parse(JSON.stringify(obj))