ReCharts: Donut Chart w/two labels in center

johnsontroye picture johnsontroye · Aug 16, 2017 · Viewed 9.5k times · Source

I have a donut chart in which i need to add two stacked labels in center which I have done. What i can't figure out is how to add a little vertical space between. ReCharts renders both these lines as SVG The chart is in a responsive container so no hard coded values. I know how to get a single label in center but can't figure out how to get two separate ones there without writing a render method for the entire chart. Suggestions?

<ResponsiveContainer>
            <PieChart >
              <Tooltip/>
              <Legend
                verticalAlign="bottom"
                align="left"
                iconType="circle"
                payload={ getCustomLegendValues(tasks) } />
              <Pie
                data={tasks}
                nameKey="name"
                dataKey="value"
                innerRadius="60%"
                outerRadius="80%"
                startAngle={90}
                endAngle={-270}
                fill="#8884d8">
                {
                  tasks.map((entry, index) => <Cell fill={ entry.color }/>)
                }
                <Label width={30} position="center">
                  { `${totalTasks} ${tasksNameLabel}` }
                </Label>
              </Pie>
            </PieChart>
          </ResponsiveContainer>

enter image description here

enter image description here

Answer

sstauross picture sstauross · Jan 3, 2018

You should use the content property of the Label component in order to create your own custom Label because both the children and the value property only accept string or numbers. With the content property you can pass a component as such:

<Label width={30} position="center"
  content={<CustomLabel value1={totalTasks} value2={tasksNameLabel}/>}>
</Label>

and the CustomLabel component:

function CustomLabel({viewBox, value1, value2}){
  const {cx, cy} = viewBox;
  return (
   <text x={cx} y={cy} fill="#3d405c" className="recharts-text recharts-label" textAnchor="middle" dominantBaseline="central">
      <tspan alignmentBaseline="middle" fontSize="26">{value1}</tspan>
      <tspan fontSize="14">{value2}</tspan>
   </text>
  )
}