Search code examples
reactjsrecharts

React Recharts data with array


I have an array of data with the following structure:

0:
  date: '01-12-2020',
  data: Array(2)
    {name: "plants", count: 5}
    {name: "water", count: 2}
1:
  date: '02-12-2020',
  data: Array(2)
    {name: "plants", count: 1}
    {name: "water", count: 4}
...

I would like to show the dates on the x-axis and render a line for each `name' category. In this case two lines, one for plants and one for water.

Should I format this code or can I use this array directly in recharts? I'm creating the array myself in the backend so I can also format it there.

I've tried something like this but it is not working:

<ResponsiveContainer width="100%" height={200}>
                <LineChart data={data}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="x" />

                    <YAxis />
                    <Tooltip />
                    {data.map((item, i) => (
                        <Line
                            dataKey={data[0].data[0].count}
                            type="monotone"
                            stroke={colors[0]}
                            activeDot={{ r: 8 }}
                        />
                    ))}
                </LineChart>
            </ResponsiveContainer>

Solution

  • Your data needs to be formatted into this :

    [{name: '01-12-2020', plants: 5 water : 4}]

    you can do as following :

       let result = [];
       data.map(entry) => {
       let obj = {date: entry.date}
         entry.data.map((entry1) => {
          obj[entry1.name] = entry1.count;
        });
       result.push(obj)
      })

    and your chart as following (your dataKey on XAxis is false)

    <ChartContainer>
      <ResponsiveContainer>
        <LineChart
          width={500}
          height={300}
          style={{ color: scoopBlue }}
          data={data}
          margin={{
            top: 5,
            right: 30,
            left: 20,
            bottom: 5
          }}
        >
          <CartesianGrid strokeDasharray="3 3" />
          <Legend />
          <Line
            type="monotone"
            dataKey="plants"
            stroke={scoopBlue}
            strokeWidth={2}
            activeDot={{ r: 5 }}
          />
            <Line
            type="monotone"
            dataKey="water"
            stroke={"orange"}
            strokeWidth={2}
            activeDot={{ r: 5 }}
           />
         </LineChart>
       </ResponsiveContainer>
    </ChartContainer>