13

Custom label for React Recharts not working with Bar chart.

http://jsfiddle.net/xpko4e7e/

 <Bar dataKey="pv"  fill="#8884d8"  label={<CustomLabel/>} />

Expected to see the 'Label' text over of all bars.

Update
For example, if I have a chart in which multiple lines are there and each line is having some label but at the time of render some of the values are above another. How to overcome with this issue?

Image Preview

Rodion
  • 233
  • 1
  • 3
  • 7

2 Answers2

20

instead of returning a div try returning a text SVG element

const CustomizedLabel = React.createClass({
  render () {
    const {x, y, stroke, value} = this.props;
  
    return <text x={x} y={y} dy={-4} fill={stroke} fontSize={10} textAnchor="middle">{value}</text>
  }
});

and then add

<Bar dataKey="pv"  fill="#8884d8"  label={customLabel} />

like I have done here, http://jsfiddle.net/CharukaK/6u08o2oa/1/

CharukaK
  • 366
  • 2
  • 9
  • To make it have more distance one can use `x={(entry.x - entry.cx) * 1.2 + entry.cx} y={(entry.y - entry.cy) * 1.2 + entry.cy}` – M at Dec 10 '21 at 00:01
7

I know this question is kind of old, but the issue is still there. We cannot use a HTML Element directly for a custom label. Only SVG Elements are working. But...

There is an element supported by SVG that is called <foreignObject>

So something like this will work:

const CustomLabel  = React.createClass({ 
  render() {  
        return (
          <g>
            <foreignObject x={0} y={0} width={100} height={100}>
              <div>Label</div>
            </foreignObject>
          </g>
        );
  }
});
service-paradis
  • 3,333
  • 4
  • 34
  • 43