Search code examples
htmlreactjswebrecharts

Recharts not rendering dynamic dataKey


I'm trying to dynamically add data keys to a line chart in Recharts. It renders the graph, but no lines.

Here is the data structure:

  const productDataset= [
    {
      name: "2023-02-18",
      flavor1: 14,
      flavor2: 10,
      flavor3: 9,
    },
    {
      name: "2023-02-19",
      flavor1: 7,
      flavor2: 9,
      flavor3: 2,
    },
    {
      name: "2023-02-20",
      flavor1: 18,
      flavor2: 21,
      flavor3: 15,
    },
  ];

And here is my rendering code:

const renderLineChart = (key) => (
   <Line type="monotone" dataKey={`${key}`} stroke="#8884d8" activeDot={{ r: 8 }} />
);

function renderChart() {
      let productArray = [];
      productDataset.forEach((date) => {
        Object.keys(date).filter((item) => {
            return item != "name";
          }).map((key) => {
            if (key != "name" && !productArray.includes(key))
            productArray.push(key);
          });
      });
      return (
        <ResponsiveContainer width="100%" height={400}>
          <LineChart
            width={1200}
            height={500}
            data={productDataset}
            margin={{
              top: 5,
              right: 30,
              left: 20,
              bottom: 5,
            }}
          >
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="name" />
            <YAxis />
            <Tooltip />
            <Legend />
            {productArray.map((key) => {
              renderLineChart(key);
            })}
          </LineChart>
        </ResponsiveContainer>
)

Also, I noticed if I replace the map function and manually call a specific flavor from one date in the object (example below), it renders the line perfectly fine, so the problem must be somewhere in the rendering code and not in the data preparation:

            <Line
              type="monotone"
              dataKey={productArray[1]}
              stroke="#8884d8"
              activeDot={{ r: 8 }}
            />

Any help is appreciated!


Solution

  • It looks like you're missing a return statement, try changing:

                {productArray.map((key) => {
                  renderLineChart(key);
                })}
    

    to:

                {productArray.map((key) => {
                  return renderLineChart(key);
                })}