-1

I'm using barchart in recharts

const data = [
  { name: 'Page A', uv: 4000, pv: 2400, color:'yellow', amt: 2400 },
];

const SimpleBarChart = (data) => ({
  return (
    <BarChart
      width={600}
      height={300} data={data}
      margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
    >
      <CartesianGrid strokeDasharray="3 3"/>
      <XAxis dataKey="name"/>
      <YAxis/>
      <Legend />
      <Bar dataKey="pv" fill={data.color} />
    </BarChart>
  );
})

I want to use color from the json. What should be the syntax of fill in the code ?

Orlyyn
  • 2,296
  • 2
  • 20
  • 32
ronnie
  • 69
  • 1
  • 10

2 Answers2

1

In order to get the color value that is stored in the first element of your data array, you just need to write the following:

<Bar dataKey="pv" fill={data[0].color} />

Because data.color yields no values, since it does not exist.

Orlyyn
  • 2,296
  • 2
  • 20
  • 32
0

You can this either by talking to the array directly by doing this;

let data = [
  { 
    name: 'Page A', 
    uv: 4000, 
    pv: 2400, 
    color:'yellow', 
    amt: 2400 
  }
];

console.log(data[0].name)

OR 
by looping through the array doing this;

for(let i=0; i<data.length; i++){
  console.log(data[i].name)
}

Samson Ugwu
  • 104
  • 2
  • 11