XEnterprise
XEnterprise

Reputation: 382

How to display React Recharts dynamically?

I am using React Recharts and I want to display it dynamically. https://recharts.org/en-US/examples/CustomActiveShapePieChart

<ResponsiveContainer width='99%' aspect={3.0 / 2.0}>
  <LineChart width={500} height={300} data={this.state.android}>
    {/* margin={{ top: 5, right: 0, left: -40, bottom: 5 }}> */}
    <XAxis dataKey="Date"/>
    <YAxis/>
    <Tooltip />
    <Legend />
    <CartesianGrid stroke="#eee" strokeDasharray="5 5"/>
    {/* "#AD7BEC"
    "#F88E4E" */}
    <Line name="android" type="monotone" dataKey="android" stroke="#ff883c" strokeWidth={2} />
    <Line name="ios" type="monotone" dataKey="ios" stroke="#ffb847" strokeWidth={2} />
  </LineChart>
</ResponsiveContainer>

This is my code for plotting line chart of recharts but I am doing this in hard code way... Now I have a data key array which is generated dynamically and now I want to pass that key to there

<Line name="android" type="monotone" dataKey="android" stroke="#ff883c" strokeWidth={2} /> 

And I want to pass element of array to datakey variable like this

dynamic_array=["android","ios","value"]
<Line name="android" type="monotone" dataKey=dynamic_array[0] stroke="#ff883c" strokeWidth={2} /> 

Can I apply map or forEach?

Upvotes: 2

Views: 6669

Answers (1)

Orlyyn
Orlyyn

Reputation: 2606

Indeed you can use the map method to create as many Line you need, just like this:

renderLines () {
  dynamic_array = ["android", "ios", "value"];
  const lines = dynamic_array.map((value) => (
    <Line
      key={value}
      name={value}
      type="monotone"
      dataKey={value}
      stroke"#ff883c"
      strokeWidth={2}
    />
  ));
  return lines;
}

And then use the result of the method within the LineChart component, like this:

<LineChart width={500} height={300} data={this.state.android}>
  <XAxis dataKey="Date"/>
  <YAxis/>
  <Tooltip />
  <Legend />
  <CartesianGrid stroke="#eee" strokeDasharray="5 5"/>
  {this.renderLines()}
</LineChart>

Upvotes: 4

Related Questions