0

How can I make the tooltip follow the cursor in a pie chart made using recharts?

Currently, a tooltip is shown but it is just stuck at a location until the cursor directly moves into it. what I need is a tooltip which moves along with the cursor. I can be at a specific position may be at the top of the chart or anything.

Demo: https://jsfiddle.net/kg7Ldj1o/

I need something like this shown in the radial bar chart.http://recharts.org/en-US/api/RadialBarChart Here the tooltip moves along with the cursor.

<PieChart width={800} height={400} onMouseEnter={this.onPieEnter}>
  <Tooltip />
  <Pie
    data={data}
    cx={420}
    cy={200}
    startAngle={180}
    endAngle={0}
    cornerRadius={40}
    innerRadius={60}
    outerRadius={80}
    fill="#8884d8"
    paddingAngle={-15}
  >
    {data.map((entry, index) => (
      <Cell
        fill={
          index === 0 || index === data.length - 1
            ? COLORS[index % COLORS.length]
            : 'transparent'
        }
        stroke={
          index === 0 || index === data.length - 1
            ? COLORS[index % COLORS.length]
            : 'transparent'
        }
      />
    ))}
  </Pie>
  <Pie
    data={data}
    cx={420}
    cy={200}
    startAngle={180}
    endAngle={0}
    cornerRadius={0}
    innerRadius={60}
    outerRadius={80}
    fill="#8884d8"
  >
    {data.map((entry, index) => (
      <Cell
        fill={
          index === 0 || index === data.length - 1
            ? 'transparent'
            : COLORS[index % COLORS.length]
        }
        stroke={
          index === 0 || index === data.length - 1
            ? 'transparent'
            : COLORS[index % COLORS.length]
        }
      />
    ))}
  </Pie>
</PieChart>;
viciousP
  • 510
  • 3
  • 14
Sagar Acharya
  • 1,763
  • 2
  • 19
  • 38

1 Answers1

1

You can listen for onMouseMove and update the left, top offset of .recharts-tooltip-wrapper element using chartX and chartY provided in the event.

Demo: jsfiddle link

I have added a function onPieEnter as bellow,

onPieEnter(e){
    console.log(e);
    if(e){
      let toolTipWrapper = document.getElementsByClassName("recharts-tooltip-wrapper")[0];
      toolTipWrapper.style.transition = 'transform 400ms ease 0s';
      toolTipWrapper.style.transform = "translate("+ (e.chartX + 10) +"px, "+ (e.chartY + 10) +"px)";
    }
}
Ejaz47
  • 145
  • 1
  • 12