Reputation: 29
I have three js file App.js
, PeopleData.js
, PeopleDetail.js
App.js
is the main application containing all other components including PeopleDetail.js
PeopleData.js
contains JSON array data that is imported to App.js
PeopleDetail.js
is the components displaying the data from PeopleData.js
But I was trying to pass the JSON from App.js
to PeopleDetail.js
as props, it would change it to an object instead of an array.
This is App.js
import React from "react";
import PeopleData from "./PeopleData";
import PeopleDetail from "./PeopleDetail";
function App() {
console.log(PeopleData)
return (
<div>
<PeopleDetail props={PeopleData} />
</div>
);
}
export default App;
Even I was using the console.log to make sure the JSON I am passing is an array, it would still end up being an object in the PeopleDetail.js
and I can't use the map function on it.
This is PeopleDetail.js
import React from "react";
function PeopleDetail(props) {
console.log(props);
const list = props.map((people) => (
<div key={people.id}>
<li>
<h1>{people.name}</h1>
</li>
</div>
));
return <div>{list}</div>;
}
export default PeopleDetail;
This is PeopleDetail.js
const peopleData = [
{
name: "Peter",
id: 1,
},
{
name: "Tom",
id: 2,
},
];
export default peopleData;
Any help would be appreciated!!! Thank you so much!
Upvotes: 0
Views: 82
Reputation: 7239
You need to pull peopleData
out of your props object. You can use a destructuring approach like below or just change your map to props.people.map(...)
. I recommend naming your attribute something other than props, so you don't get confused with the normal props object. Right now you have an props object with a props array.
import React from "react";
import PeopleData from "./PeopleData";
import PeopleDetail from "./PeopleDetail";
function App() {
console.log(PeopleData)
return (
<div>
<PeopleDetail people={PeopleData} />
</div>
);
}
export default App;
import React from "react";
function PeopleDetail({ people }) {
console.log(people);
const list = people.map((person) => (
<div key={person.id}>
<li>
<h1>{person.name}</h1>
</li>
</div>
));
return <div>{list}</div>;
}
export default PeopleDetail;
Upvotes: 1