'How can I map array with multiple objects and display on chart?
I want to display my data that I collect from firestore database and show it on charts, using Rechart in React. This is how my data looks like:
When I want to display everyting on one chart - everything works fine. But I want to create that many single charts how much objects I have. I mean, every new trip = new chart.
This is how my code looks like right now.
Saving data into array
const getData = async () => {
const data = [];
const querySnapshot = await getDocs(
collection(databaseRef, `${cUser}/userinfo/trips`)
);
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data().Title);
data.push({
Trip: doc.data().Trip,
Distance: doc.data().Distance,
Time: doc.data().Time,
Calories: doc.data().Calories,
});
});
setData(data);
console.log(data);
};
This code generate 2 different charts, what is OK but without any data.
{dataToShow.map((item) => {
return (
<>
<BarChart width={600} height={600} data={item}>
<XAxis dataKey={item.Trip} />
<YAxis dataKey={item.Distance} />
<Bar dataKey={item.Calories} barSize={30} fill="#8884d8" />
<Bar dataKey={item.Time} barSize={30} fill="#fcba03" />
</BarChart>
</>
);
})}
What's wrong with my mapping?
Thanks for any help!
Solution 1:[1]
To display your different Bar elements, you don't need to loop into every item of your array.
Instead, you just need to use the prop dataKey per Bar, where you specify the data you want to use as a string, just like the following:
// {dataToShow.map((item) => { <-- remove this
return (
<BarChart width={600} height={600} data={dataToShow}> // update the `data` prop with your data array
<XAxis dataKey="Trip" />
<YAxis dataKey="Distance" />
<Bar dataKey="Calories" barSize={30} fill="#8884d8" />
<Bar dataKey="Time" barSize={30} fill="#fcba03" />
</BarChart>
);
// })} <-- to remove
Recharts will understand the data you're pointing to with the same prop name ("Trip", and so on).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Orlyyn |

