How to pass fill colors to recharts Pie component

Viewed 4922

So basically i have this array of objects:

const testMeasurments = [
  {
    data: [
      {name: "glucose", value: 6, color: '#57c0e8'},
      {name: "SpO2", value: 5, color: "#FF6565"},
      {name: "Blood Pressure", value: 4, color: "#FFDA83"},
      {name: "Body Weight", value: 2, color: "purple"}
    ]
  }
]

I want to loop over them and access the color property. So basically i have a chart and each part will have its own color so I want to loop inside the object while assigning the value also to assign the color to it.

Example:

{testMeasurments.map(s=>
        <Pie 
        dataKey="value" 
        isAnimationActive={false} 
        data={s.data} 
        cx={200} 
        cy={200} 
        outerRadius={100} 
        innerRadius={60}
    fill={s.color} // Here I want to loop over each color and assign it to the proper value
  >

As you can see it is certainly not working here but thats what i need! Thank you in advance.

3 Answers

Looking at the code example for the Pie component, you need to rename the color property to fill in your data set, and then it will automatically work. The fill property on the Pie component is for the component-level filling color.

const testMeasurments = [
  {
    data: [
      {name: "glucose", value: 6, fill: '#57c0e8'},
      {name: "SpO2", value: 5, fill: "#FF6565"},
      {name: "Blood Pressure", value: 4, fill: "#FFDA83"},
      {name: "Body Weight", value: 2, fill: "purple"}
    ]
  }
]

/// ...

{testMeasurments.map(s=>
        <Pie 
        dataKey="value" 
        isAnimationActive={false} 
        data={s.data} 
        cx={200} 
        cy={200} 
        outerRadius={100} 
        innerRadius={60}
        fill="#fff"
  >

try something like this:

testMeasurments.map((tm) => {
   return tm.data.map((data) => {
       <Pie 
         dataKey="value" 
         isAnimationActive={false} 
         data={data.data} 
         cx={200} 
         cy={200} 
         outerRadius={100} 
         innerRadius={60}
         fill={data.color}
   })
}

If you are passing testMeasurements as a prop, then you need to take the first element of the testMeasurements array and then you can access the data array and then you can loop over like this -

{
    this.props.testMeasurements[0].map(dataSet => (
        <Pie
         dataKey="value" 
         isAnimationActive={false} 
         data={dataSet.data} 
         cx={200} 
         cy={200} 
         outerRadius={100} 
         innerRadius={60}
         fill={dataSet.color}
        />
    ))
}
Related