How to Display Values Next to Legend in React Pie Chart? Getting 'Undefined' Error

29 Views Asked by At

I am trying to display value next to legend, but I am getting undefined. Debugged but no luck, can you let me know how to fix it.

Providing my code snippet and stackblitz below

https://stackblitz.com/edit/react-piechart-padding-complete-8jdttg?file=index.js

status_pie_data: [
  // {"name":"On Arrival","value":0},
  { name: 'Daily', value: 100 },
  { name: 'Weekly', value: 20 },
  { name: 'Monthly', value: 30 },
  { name: 'One Time', value: 50 },
  // {"name":"Active","value":0},
  // {"name":"Completed","value":0}
],

<Legend
            layout="vertical"
            verticalAlign="middle"
            align="right"
            wrapperStyle={{
              fontFamily: 'Lato',
              fontWeight: 400,
              fontColor: '#000',
              fontSize: '9pt',
              marginRight: '0px',
            }}
            formatter={(value, entry, index) => `${entry.name}: ${value}`} // Customize formatter
1

There are 1 best solutions below

0
Elna Haim On

In order to achieve it you need to use the content prop. the prop needs to return JSX element (can be array). we will use map to loop through the payload and we will render the values we need:

           <Legend
            layout="vertical"
            verticalAlign="middle"
            align="right"
            wrapperStyle={{
              fontFamily: 'Lato',
              fontWeight: 400,
              fontColor: '#000',
              fontSize: '9pt',
              marginRight: '0px',
            }}
            content={(obj) =>
              obj.payload.map((item) => (
                <div>
                  {item.value}: {item.payload.value}
                </div>
              ))
            }
          />

To know what more info you are getting in the content obj you can console log it.

if you console log each item from obj.payload you will see:

color: "#ffb2b2"
payload: Object
type: "rect"
value: "One Time"

and the item.payload is:

cornerRadius: undefined
cx: 125
cy: 125
endAngle: 360
fill: "#ffb2b2"
innerRadius: 50
maxRadius: 169.7056274847714
midAngle: 315
middleRadius: 73
name: "One Time"
outerRadius: 96
paddingAngle: 0
payload: Object
percent: 0.25
startAngle: 270
stroke: "#ffffff"
strokeLinecap: "round"
strokeWidth: "5px"
tooltipPayload: Array[1]
tooltipPosition: Object
value: 50

I recommend you to console log the data your self and see if you find any other valuable value you can use there.

This method will help you to create your own design for the legend.

If you want to use the formatter prop. the formatter prop is recieving the value only. there for you will need to find inside your status_pie_data arraythe object with name === value and render the info from there. if you want i can edit the answer with a code example