Algorithm Unlock
Algorithm Unlock

Reputation: 119

How to get only hovered line item instead of all line items of y axis in recharts?

There are two lines in the graph(Attendance & Video Watched). When I hover on Attendance line, in payload variable of CustomTooltip is getting two entries (i.e one entry for each line in the graph).

How to get only attendance line entry when hovered on Attendance line?

    <Line
      type="linear"
      dataKey="overall_attendance"
      stroke="#82ca9d"
      strokeWidth={3}
      label="Attendance"
    />
    <Line
      type="linear"
      dataKey="video_watched_percentage"
      strokeWidth={3}
      label="Video Watched"
    />
    <Tooltip content={<CustomTooltip />} shared={false} />
  </LineChart>
const CustomTooltip = ({ active, payload, label }: any) => {
console.log('payload ', payload)
// I want this payload to the respective line, instead of all lines for the same X axis value

return null
}

MUI X Charts does something like this 'item' —when the user's mouse hovers over an item on the chart, the tooltip will display data about this specific item. 'axis' —the user's mouse position is associated with a value of the x-axis. The tooltip will display data about all series at this specific x value.

REf: https://mui.com/x/react-charts/tooltip/#interactions

How to achieve this item option behaviour using recharts?

These are the logs from CustomTooltip component. I am getting four items from all lines in payload, how do i get which line item it is from? enter image description here

Update You can refer this sandbox example: https://codesandbox.io/s/recharts-multi-linemulti-data-sourcse-81u1y?file=/src/App.js

How to show OIL only if I hover on violet line in the graph?

Upvotes: 0

Views: 708

Answers (1)

Afzal K.
Afzal K.

Reputation: 933

filtering out the data in the payload based on the active data key, which is the name of the line that is being hovered over.

const CustomTooltip = ({ active, payload, label }) => {
  if (active) {
    const activeDataKey = payload[0]?.dataKey; // get name of hovered over
    const filteredPayload = payload.filter(
      (item) => item.dataKey === activeDataKey // filter out active line
    );
    
    // show tooltip info using filtered payload
    return (
      <div>
        <p>{label}</p>
        {filteredPayload.map((item, index) => (
          <p key={index}>{`${item.name} : ${item.value}`}</p>
        ))}
      </div>
    );
    
  }
  return null;
};

<Tooltip content={<CustomTooltip />} shared={false} />

ensures that only the data for the hovered line is displayed in the tooltip.

Upvotes: 0

Related Questions