Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  77] [ 2]  / answers: 1 / hits: 5260  / 3 Years ago, sun, july 11, 2021, 12:00:00

I'm having an issue while creating a custom tooltip using react-chartjs-2 library where my chart rerenders whenever I hover the chart and change the state of the tooltip's future data. (currently tooltip doesn't exist I'm simply logging some data which Ill use later)


I referenced this question while trying to create a tooltip however they are using a class component and I use functional component but it shouldn't really change anything but anyway. I'd be really grateful of someone could provide a working example of a custom tooltip with react-chartjs-2 because I'm still not sure whether tooltip should be a separate jsx component or what is the proper way to create a custom tooltip in React. Thanks in advance


My code


 const GraphTooltip = ({ data }) => {
return (
<div
style={{
padding: 20,
position: 'absolute',
border: '1px solid',
borderColor: '#fff8f9',
backgroundColor: 'rgba(53,53,53,0.81)',
borderRadius: 4,
top: data.top,
left: data.left,
}}
></div>
);
};

const LineChart = ({ values, labels }) => {
const isSSR = useIsSSR();

const [tooltipData, setTooltipData] = useState(null);

console.log(tooltipData);

const chartRef = useRef(null);

const customTooltip = useCallback(tooltipModel => {
if (tooltipModel.tooltip.opacity == 0) {
setTooltipData(null);
console.log('Hide tooltip');
return;
}
console.log(tooltipModel);
const chart = chartRef.current;
const canvas = chart.canvas;

console.log(canvas);

if (canvas) {
const position = canvas.getBoundingClientRect();

// set position of tooltip
const left = tooltipModel.tooltip.x;
console.log(position.left);
console.log(tooltipModel.tooltip);
const top = tooltipModel.tooltip.y;

tooltipData?.top != top && setTooltipData({ top: top, left: left });
}
});

const options = useMemo(() => ({
scales: {
x: {
ticks: {
beginAtZero: true,
},
grid: {
color: '#EEF5FF',
},
},
y: {
grid: {
color: '#EEF5FF',
},
},
},
plugins: {
legend: {
display: false,
position: 'right',
},
tooltip: {
enabled: false,
external: customTooltip,
},
},
}));

const data = {
labels: labels,
datasets: [
{
data: values,
fill: false,
backgroundColor: '#88B1DD',
borderColor: '#88B1DD',
pointRadius: 6,
tension: 0.5,
},
],
};

if (isSSR) return null;

return (
<>
<div className="header"></div>
<div className="relative">
<Line data={data} options={options} ref={chartRef} />
{tooltipData ? <GraphTooltip data={tooltipData} /> : <div />}
</div>
</>
);
};

More From » reactjs

 Answers
4

Using https://www.npmjs.com/package/test-react-chartjs-2 actually fixed this. Some problems in the package itself.


[#1114] Sunday, July 4, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hailey

Total Points: 355
Total Questions: 91
Total Answers: 91

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;