Could do with some help on a react app. I am trying to map an array of objects that has been passed down form the parent but it comes up with the error:
TypeError: Cannot read properties of undefined (reading ‘map’)
I can JSON.stringify as below and I can map the same array if it is defined in same file. Just can’t map as a prop sent from parent.
Could someone point me in the right direction on how to map an array as below in the child component sent from parent.
const tracks = [
{
id: 1,
name: "Song 1",
artist: "Artist 1",
album: "Album 1"
},
{
id: 2,
name: "Song 2",
artist: "Artist 2",
album: "Album 2"
},
];
Thanks for any advice
const App = () => {
const mockData = "Song 1";
const mockData1 = [
{
id: 1,
name: "Song 1",
artist: "Artist 1",
album: "Album 1"
},
{
id: 2,
name: "Song 2",
artist: "Artist 2",
album: "Album 2"
},
];
return (
<div>
<h1>
Ja<span className="highlight">mmm</span>ing
</h1>
<div className="App">
<SearchBar />
< div className="App-playlist">
<SearchResults
mockData={mockData}
mockData1={mockData1}
appObject={{
id: 1,
name: "Song 1",
album: "Album 1",
artist: "Artist 1"
}}
/>
<Playlist />
<>
{mockData1.map((item) => (
<div key={item.id}>
<div>{item.name}</div>
<div>{item.album}</div>
<div>{item.artist}</div>
</div>
))}
</>
</div>
</div>
</div>
);
};
export default App;
const SearchResults = (props) => {
return (
<div className="SearchResults">
<h2>Results</h2>
<TrackList
mockData={props.mockData}
appObject={props.appObject}
tracks={props.mockData1}
/>
</div>
);
};
export default SearchResults;
const TrackList = (props) => {
return (
<div className="TrackList">
<Track
mockData={props.mockData}
appObject={props.appObject}
/>
<p>
{JSON.stringify(props.tracks)}
</p>
{props.tracks.map((item) => (
<div key={item.id}>
<div>{item.name}</div>
<div>{item.album}</div>
<div>{item.artist}</div>
</div>
))}
</div>
);
};
export default TrackList;
props.tracks.map – causing issue
2
Answers
Since you haven’t mentioned your code, therefore, I will provide a basic example of sending an array of objects from the parent component to the child component.
Parent Component
Child Component
Feel free to customize the code according to your specific requirements. This example serves as a starting point for passing an array of objects from a parent component to a child component in React.
If you find this response helpful, I kindly request you to consider upvoting and marking it as the approved answer. Your feedback is valuable in helping other users recognize useful content and demonstrates your appreciation for the assistance provided.
If your
Data
is coming from an api try to do this:And make sure that the
prop?.array
is an array not object or something else (because maybe the api returns an object…).