How to Build a Tooltip That Shows Values on a React Line Chart
A tooltip for a line chart can be built by finding the "nearest point" from the horizontal position of the pointer. The thing to watch out for is that the screen pixel coordinates and the SVG viewBox coordinates stop matching once the chart is scaled down. If you convert the coordinates with getScreenCTM() before choosing the point, the value of the hovered point shows up even at smartphone widths.
Without using a library, I built a LineChart component. When the pointer moves over the chart, a vertical dashed line and a circle appear on the nearest month, and that month's value is shown in a tooltip. The data is made-up numbers.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx with tsc, transpiled it with esbuild, and used Playwright to drive Chromium. Touch was tested with Playwright's touch device settings and with touch input sent through the Chrome DevTools Protocol. I did not test on a real smartphone. I did not test Firefox or Safari, pen input, or screen reader announcements. I did not handle data whose points are not evenly spaced, such as irregular time series with gaps in dates.

Converting the pointer position to viewBox coordinates
I put the coordinate calculations in a single file. The x of a point is its position when the space between the left and right margins is divided equally by one less than the number of points. For y, a value of 0 maps to the bottom edge and max maps to the top edge.
export type Point = { label: string; value: number };
// Chart size (in viewBox units) and margins for the axis text
export const W = 640;
export const H = 300;
export const PAD = { top: 16, right: 16, bottom: 32, left: 48 };
export const PLOT_W = W - PAD.left - PAD.right;
export const PLOT_H = H - PAD.top - PAD.bottom;
// x of the i-th point and y of value v (both in viewBox units)
export const xAt = (i: number, n: number) => PAD.left + (n > 1 ? (PLOT_W * i) / (n - 1) : PLOT_W / 2);
export const yAt = (v: number, max: number) => PAD.top + PLOT_H * (1 - v / max);
// Convert the pointer position on screen (clientX, clientY) to viewBox coordinates
export function toSvgPoint(svg: SVGSVGElement, clientX: number, clientY: number): DOMPoint | null {
const m = svg.getScreenCTM();
if (!m) return null;
return new DOMPoint(clientX, clientY).matrixTransform(m.inverse());
}
// Index of the nearest point for an x in viewBox units (the points are evenly spaced)
export function nearestIndex(x: number, n: number): number {
if (n <= 1) return 0;
const i = Math.round(((x - PAD.left) / PLOT_W) * (n - 1));
return Math.min(n - 1, Math.max(0, i));
}
According to the getScreenCTM entry in the SVG 2 specification, getScreenCTM() returns a matrix that maps the element's coordinates to the browser's viewport coordinates. This matrix includes the scaling from the viewBox and the position of the <svg> on the page. Despite the name "Screen," the reference is the same viewport that clientX and clientY use, and the specification notes that a name like getClientCTM would have been more appropriate. Multiplying the inverse matrix (inverse()) by the point at clientX and clientY using matrixTransform() converts it back to viewBox coordinates.
You can also use offsetX, and if you receive the event on the <svg> itself, you get the distance from the left edge of the <svg>. However, its unit is screen pixels. The viewBox width is 640, so while the chart is displayed at 640px, the pixel values and viewBox coordinates are the same, and the difference goes unnoticed.
On a 375px-wide screen, the chart was 343px wide. When I placed the cursor on each month's x and compared, every month was correct when I converted with getScreenCTM(). When I used offsetX directly as the viewBox coordinate, the result was off as follows:
| Month under cursor | offsetX | Month shown when offsetX is used directly |
|---|---|---|
| April | 109.9 | February |
| September | 250.2 | May |
| December | 334.4 | June |

Screen pixels are smaller numbers than viewBox coordinates, so the farther right you go, the further left the month shown lags behind the cursor. Even at December, it only reaches June.
Choosing the nearest point
nearestIndex converts the viewBox x into a fractional point index and rounds it with Math.round. The boundary is midway between two points, and the closer point is chosen. On an 800px-wide screen, placing the cursor exactly 2 viewBox units left of the midpoint between March and April showed "March 410 visitors", and 2 units to the right showed "April 460 visitors".
When the cursor is on the left or right margin, the index is clamped with Math.min and Math.max so it never goes below 0 or reaches the number of points. Placing the cursor on the left margin (where x is 10) selected the January point, with its center at (48, 167.2), which is the position of January's value of 320.
The vertical position is not used, so as long as x is the same, the same point is selected at any height. At June's x, even when placed on the height of the horizontal axis text, "June 350 visitors" was shown. For a line chart, I think this is easier to use, because you can read the value without aiming right at the line. This calculation assumes the points are evenly spaced.
The LineChart code
This is a component that bundles the pointer handling, keyboard handling, and the tooltip.
import { useState, type KeyboardEvent, type PointerEvent } from 'react';
import { H, PAD, PLOT_H, W, nearestIndex, toSvgPoint, xAt, yAt, type Point } from './chart';
type Props = {
data: Point[];
title: string;
max: number; // Value at the top of the vertical axis
unit?: string;
};
export function LineChart({ data, title, max, unit = '' }: Props) {
const [active, setActive] = useState<number | null>(null);
const n = data.length;
const points = data.map((d, i) => `${xAt(i, n)},${yAt(d.value, max)}`).join(' ');
const pick = (e: PointerEvent<SVGSVGElement>) => {
const p = toSvgPoint(e.currentTarget, e.clientX, e.clientY);
if (p) setActive(nearestIndex(p.x, n));
};
// pointerleave also arrives after the finger is lifted, so clear only for mouse
const leave = (e: PointerEvent<SVGSVGElement>) => {
if (e.pointerType === 'mouse') setActive(null);
};
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const next: Record<string, number> = {
ArrowRight: active === null ? 0 : Math.min(n - 1, active + 1),
ArrowLeft: active === null ? n - 1 : Math.max(0, active - 1),
Home: 0,
End: n - 1,
};
if (e.key in next) {
e.preventDefault();
setActive(next[e.key]);
} else if (e.key === 'Escape') {
setActive(null);
}
};
const sel = active === null ? null : data[active];
const selX = active === null ? 0 : xAt(active, n);
const text = sel ? `${sel.label} ${sel.value}${unit}` : '';
return (
<div
className="line-chart"
tabIndex={0}
role="group"
aria-label={`${title}(左右の矢印キーで値を読む)`}
onKeyDown={onKeyDown}
onBlur={() => setActive(null)}
>
<svg
viewBox={`0 0 ${W} ${H}`}
aria-hidden="true"
onPointerMove={pick}
onPointerDown={pick}
onPointerLeave={leave}
>
{[0, 0.5, 1].map((t) => (
<g key={t}>
<line x1={PAD.left} x2={W - PAD.right} y1={yAt(max * t, max)} y2={yAt(max * t, max)} stroke="#d5dde0" />
<text x={PAD.left - 8} y={yAt(max * t, max) + 4} textAnchor="end" fontSize={12} fill="#5b6870">
{max * t}
</text>
</g>
))}
{data.map((d, i) => (
<text key={d.label} x={xAt(i, n)} y={H - 10} textAnchor="middle" fontSize={12} fill="#5b6870">
{d.label}
</text>
))}
<polyline points={points} fill="none" stroke="#00c8e8" strokeWidth={3} strokeLinejoin="round" />
{sel && (
<>
<line className="guide" x1={selX} x2={selX} y1={PAD.top} y2={PAD.top + PLOT_H} stroke="#9aa5ab" strokeDasharray="4 4" />
<circle className="dot" cx={selX} cy={yAt(sel.value, max)} r={6} fill="#fff" stroke="#067a98" strokeWidth={3} />
</>
)}
</svg>
{sel && (
<div
className="tip"
aria-hidden="true"
style={{
left: `${(selX / W) * 100}%`,
top: `${(PAD.top / H) * 100}%`,
// On points in the right half, show the tooltip on the left side of the line
transform: active! > (n - 1) / 2 ? 'translateX(calc(-100% - 10px))' : 'translateX(10px)',
}}
>
<span className="tip-label">{sel.label}</span>
<strong>
{sel.value}
{unit}
</strong>
</div>
)}
<p className="visually-hidden" aria-live="polite">
{text}
</p>
</div>
);
}
On the calling side, pass the pairs of labels and values, and the top value of the vertical axis.
import { LineChart } from './LineChart';
import type { Point } from './chart';
// Example data (made-up numbers)
const visitors: Point[] = [
{ label: '1月', value: 320 },
{ label: '2月', value: 280 },
{ label: '3月', value: 410 },
{ label: '4月', value: 460 },
{ label: '5月', value: 390 },
{ label: '6月', value: 350 },
{ label: '7月', value: 520 },
{ label: '8月', value: 580 },
{ label: '9月', value: 430 },
{ label: '10月', value: 470 },
{ label: '11月', value: 500 },
{ label: '12月', value: 610 },
];
export function App() {
return <LineChart data={visitors} title="月ごとの来店数" max={800} unit="人" />;
}
The selected point's index is kept in active, and when it is null, nothing is shown. onPointerMove recalculates the index every time the pointer moves, and when the mouse leaves the chart (onPointerLeave), it returns to null. As described in the official reference for common props, handlers such as onPointerMove can be attached to all built-in elements. React also supports all built-in SVG elements, so the handler can be attached to <svg> directly. The lines and text on the chart are children of <svg>, so wherever the cursor is on the chart, the <svg> handler is called. Once the pointer leaves, the tooltip and circle both disappeared.
The CSS for the tooltip and the vertical line is as follows.
.line-chart { position: relative; max-width: 640px; }
.line-chart svg { display: block; width: 100%; height: auto; touch-action: pan-y; }
.line-chart:focus-visible { outline: 2px solid #067a98; outline-offset: 4px; }
.tip { position: absolute; pointer-events: none; white-space: nowrap; padding: 6px 10px; border-radius: 6px; background: #1f2a30; color: #fff; font-size: 14px; line-height: 1.4; }
.tip-label { display: block; font-size: 12px; color: #c9d3d8; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; margin: 0; }
The axis labels are 12 units in viewBox size. When the chart is shrunk to 343px, the text shrinks by the same ratio. How text size changes with the screen width, and how to counter that, are covered in my other article on this blog, "How to Draw a Bar Chart with SVG in React Without a Library."
Overlay the tooltip in HTML and specify its position as a percentage
I made the tooltip a HTML <div> overlaid on the chart, not an SVG <text>. With HTML, the text size is determined in screen pixels, so it does not shrink when the chart is scaled down. On a 375px-wide screen, the tooltip was 58.8px wide for every month. The background and corner rounding can also be set with CSS.
The position is specified by converting the viewBox coordinates into percentages of the chart's width and height. left is "point x ÷ 640," and top is "top margin ÷ 300." If the outer <div> has position: relative, the tooltip stays next to the vertical line at any pixel size of the chart, since the percentages stay the same. There is no need to re-measure the chart's size on screen.
If the tooltip for the rightmost point appeared on the right, it would overflow the chart. So for points in the right half (July through December), I use translateX(calc(-100% - 10px)) to shift the tooltip left by its own width, placing it on the left side of the vertical line. These are the positions I measured on a 375px-wide screen (the chart's left edge at 16 and right edge at 359):
| Month | Vertical line x | Tooltip left–right edges | Side shown |
|---|---|---|---|
| January | 41.5 | 51.7–110.5 | Right |
| June | 181.8 | 192.0–250.8 | Right |
| July | 209.8 | 141.3–200.1 | Left |
| December | 350.2 | 281.6–340.4 | Left |
When I changed December to show the tooltip on the right, its right edge was at 419.2, which went past the screen width (375). The tooltip has pointer-events: none. Without it, the tooltip is an element placed next to <svg> rather than a child of it, so when the cursor reaches the tooltip, it counts as having left <svg>. I also tested a version without pointer-events: none on an 800px-wide screen. With March selected, moving the cursor onto the tooltip sent pointerleave to <svg>, and the tooltip disappeared. Once it disappeared, the area under the cursor returned to <svg>, which sent pointerenter, so the tooltip appeared again on the next move. When I moved the pointer 1px at a time six times to the right while over the tooltip, it appeared and disappeared three times. With pointer-events: none, "March 410 visitors" remained visible under the same movement. Because the tooltip is placed at the top edge of the chart, when a point such as August or September is selected, the tooltip covers the part of the line with large values (around July and August).
This article decides which side to show the tooltip on based only on the point's position. For a method that measures the tooltip's width and decides based on whether it fits, see my other article on this blog, "How to Show a Tooltip in React Without Overflowing the Screen Edge."
On touch, do not clear the tooltip when the finger is lifted
On a smartphone, touching the chart with a finger fires pointerdown. Because onPointerDown calls the same handler, the value of the tapped point is shown.
The problem is when the finger is lifted. When I tapped March as a touch device in Playwright, the events arrived in the order pointerdown, pointerup, and pointerleave. All of them had pointerType set to touch. MDN's explanation of pointer events also says that for input such as a finger, which cannot hover, pointerout (an event that notifies that the pointer has left an element) is sent after pointerup. In my test, pointerleave also arrived in the same way. In a version that always cleared the tooltip on pointerleave, the tooltip disappeared right after the finger was lifted, even after a tap.
So I clear the tooltip only when pointerType is mouse. In this version, "March 410 visitors" remained visible after tapping March. The code is also written so the tooltip does not disappear when pointerType is pen.
To let people drag a finger across the chart horizontally and read the values in order, add touch-action: pan-y to <svg>. According to MDN's explanation of touch-action, by default the browser handles finger scrolling and zooming, and once the browser takes over, the page receives pointercancel. pan-y is a setting that leaves only vertical scrolling to the browser.
I compared the results by sending touch input through the Chrome DevTools Protocol, moving a finger from January to December in 22 separate steps:
| touch-action | pointermove | pointercancel | Months shown in the tooltip |
|---|---|---|---|
| pan-y | 22 | 0 | All, from January to December |
| auto (not set) | 2 | 1 | January, February |
Without the setting, after two moves the browser took over the gesture as scrolling, sent pointercancel, and the later movements did not reach the page. Even with pan-y, when I dragged the finger vertically 150px over the chart, the page scrolled (scrollY was 174). With touch-action: none, vertical scrolling over the chart is also disabled, which makes it hard to use on pages where the chart takes up most of the screen.
Make the values readable with the keyboard too
For people who use neither a mouse nor touch, I wrapped the whole chart in a <div> with tabIndex={0}, so the points can be selected with the left and right arrow keys. Home selects the first point, End selects the last point, and Escape clears the selection. The selection is also cleared when focus leaves (onBlur).
After moving focus to the chart with the Tab key and pressing keys in sequence, the tooltip changed as follows:
| Key pressed | Tooltip |
|---|---|
| → | January 320 visitors |
| → | February 280 visitors |
| End | December 610 visitors |
| ← | November 500 visitors |
| Home | January 320 visitors |
| Escape | (disappears) |
The tooltip <div> has aria-hidden="true", so it is not used for screen reader output. Instead, the same text is placed in a visually hidden <p> with aria-live set to polite. According to MDN, when the content of an element with aria-live="polite" changes, assistive technology usually announces the change without interrupting what the user is currently doing. In testing, each press of an arrow key changed the content of this <p> to the same text as the tooltip, such as "January 320 visitors."
In the accessibility tree of Chromium, retrieved with Playwright, the chart appeared as a group named "Monthly visitor count (read values with the left and right arrow keys)." The <svg> that draws the lines and axis text has aria-hidden="true", so it does not appear in the tree. The name itself tells the user that there is a way to read values with the keys.





