I'm working on a react
project.
I have an array of objects in Parent component now how to pass an array of objects from parent to child in react
Parent.Component
import React from 'react';
import './App.css';
import Child from './Child/Child';
function App() {
const students = [
{
name: "Mark",
age: 21
},
{
name: "Williams",
age: 24
}
]
return (
<div className='App'>
<Child studentsArrayOfObject = { students }></Child>
</div>
)
}
export default App
Child.Component
import React from "react";
import "./Child.css";
function Child(props) {
return (
<div className="container">
<div className="row">
<div className="col-12">
<div className="Child">
{props.studentsArrayOfObject.map(student => (
<li>{student}</li>
))}
</div>
</div>
</div>
</div>
);
}
export default Child;
you are not suppose to print object directly, get some property from the object, and display like below. ex:name.
{props.studentsArrayOfObject.map(student => <li>{student.name}</li>)}
Try to fetch the properties of the objects and render it in JSX.You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. Change your Child component to the following Example
import React from 'react';
import './Child.css';
function Child(props) {
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div className='Child'>
{props.studentsArrayOfObject.map(student => (
<li key={student.name}>{student.name}</div>
<li key={student.age}>{student.age}</div>
))}
</div>
</div>
</div>
</div>
)
}
export default Child
You can not just render the student object, I changed it to student.name
here.
<div className="Child">
{/* {props.studentsArrayOfObject.map(student => (
<li>{student}</li>
))} */}
{props.studentsArrayOfObject.map(student => (
<li>{student.name}</li>
))}
</div>
Here is an online demo: https://codesandbox.io/s/so-60612610-y9y5z
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.