Ashwin R
Ashwin R

Reputation: 787

Rechart custom tooltip for X-axis labels on a PositiveAndNegativeBarChart

I'm trying to build a bar chart using recharts. The labels text on the x-axis are long, more than 100 characters.

I want to display, item 1, item 2, item 3. And when i hover the mouse around it, i want a tooltip to show the actual description for the item. I'm unable to implement this with recharts. enter image description here

Thanks in advance !

I have tried using Rechart's custom tooltip. But Rechart's tooltip will highlight the entire graph, I just need a functionality to display a custom tooltip on hover on each of the x-axis labels.

Upvotes: 0

Views: 1178

Answers (1)

stasdes
stasdes

Reputation: 669

you can wrap your chart with relative div and then listen to onMouseEnter onMouseLeave on XAxis component and render your custom tooltip, something like this:

const TooltipAxis = () => {
  const [tooltip, setTooltip] = useState(null)

  const renderTooltip = () => {
    if (tooltip?.index === undefined) return null
    return <div style={{ 
      position: 'absolute',
      left: tooltip.coordinate - 70, 
      bottom: 80, 
      overflow: 'visible', 
      width: 150, 
      background: 'white', 
      border: '1px solid grey', 
      borderRadius: 50
    }}>
      {data[tooltip.index].description}
    </div>
  }

  return (
    <div style={{ width: 500, height: 300, position: 'relative' }}>
      <ResponsiveContainer width="100%" height="100%">
        <LineChart data={data}>
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="name" height={60} onMouseEnter={(params) => setTooltip(params)} onMouseLeave={() => setTooltip(null)}/>
          <YAxis />
          <Line type="monotone" dataKey="uv" stroke="#82ca9d" />
        </LineChart>
      </ResponsiveContainer>
      {renderTooltip()}
    </div>
  );
}

export default TooltipAxis

Upvotes: 0

Related Questions