Creating Custom Tooltip in Recharts
Demonstrates how to create a custom tooltip component in Recharts by leveraging the 'content' prop of the Tooltip component.
import React from 'react';
import { Tooltip, ResponsiveContainer, LineChart, Line, XAxis, YAxis, CartesianGrid } from 'recharts';
Import necessary components from Recharts library.
const CustomTooltip = ({ active, payload, label }) => {
if (active && payload && payload.length) {
return (
<div className='custom-tooltip'>
<p className='label'>{`${label}: ${payload[0].value}`}</p>
</div>
);
}
return null;
};
Define a custom tooltip component. It checks if the tooltip is active and if there is data (payload). If so, it renders a custom styled tooltip displaying the data.
const data = [
{ name: 'A', uv: 4000, pv: 2400 },
{ name: 'B', uv: 3000, pv: 1398 },
...
];
Define the data to be used in the chart.
const SimpleLineChart = () => (
<ResponsiveContainer width='100%' height={300}>
<LineChart data={data}>
<XAxis dataKey='name'/>
<YAxis/>
<CartesianGrid strokeDasharray='3 3'/>
<Tooltip content={<CustomTooltip />}/>
<Line type='monotone' dataKey='pv' stroke='#8884d8' />
<Line type='monotone' dataKey='uv' stroke='#82ca9d' />
</LineChart>
</ResponsiveContainer>
);
Integrate the custom tooltip component into a LineChart component. The ResponsiveContainer makes the chart responsive.
export default SimpleLineChart;
Export the chart component.