Building a Drag-to-Turn Rotary Knob in React
If you take the pointer's direction as seen from the knob's center, get it with Math.atan2, and add the difference from the previous direction to the knob's angle, you can build a drag-to-turn dial with React alone. You can also set the knob's angle directly to the pointer's direction, but in that version the value jumped from the maximum to 0 the moment the pointer passed straight down.
What I built is a Knob component that picks a volume from 0 to 100. The knob turns 270 degrees in total, 135 degrees to each side of straight up (0 degrees). It works with mouse and finger drags, and also with the keyboard.
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, and Playwright 1.63.0. I operated the mouse and keyboard with Playwright. For touch, I used the Chrome DevTools Protocol (CDP) Input.dispatchTouchEvent on a screen that imitated a smartphone's display. I did not test on a real smartphone, in Firefox or Safari, or with a screen reader. This article does not cover mouse wheel operation.

- 1. The whole Knob component
- 2. Getting the pointer angle with Math.atan2
- 3. Adding up the delta from the last event so the value doesn't jump past the bottom
- 4. Keeping the drag going after the pointer leaves the knob
- 5. Setting touch-action: none for finger dragging
- 6. Making it work with the keyboard
- 7. Drawing the scale arc in degrees with pathLength
The whole Knob component
First, here is the full code. The look is drawn with SVG, and the drag is received through Pointer Events.
import { useRef } from 'react';
import type { KeyboardEvent, PointerEvent } from 'react';
type Props = {
label: string;
value: number;
min?: number;
max?: number;
step?: number;
onChange: (value: number) => void;
};
// Range the knob can turn (0 degrees is straight up, clockwise is positive)
const MIN_ANGLE = -135;
const MAX_ANGLE = 135;
function clamp(n: number, lo: number, hi: number) {
return Math.min(hi, Math.max(lo, n));
}
// Direction of the pointer as seen from the element's center (-180 to 180 degrees)
function pointerAngle(el: HTMLElement, x: number, y: number) {
const r = el.getBoundingClientRect();
const dx = x - (r.left + r.width / 2);
const dy = y - (r.top + r.height / 2);
return (Math.atan2(dx, -dy) * 180) / Math.PI;
}
type Drag = {
pointerId: number;
lastAngle: number; // Pointer direction at the previous pointermove
rotation: number; // Knob angle (keeps fractional parts as it accumulates)
};
export function Knob({ label, value, min = 0, max = 100, step = 1, onChange }: Props) {
const drag = useRef<Drag | null>(null);
const toAngle = (v: number) => MIN_ANGLE + ((v - min) / (max - min)) * (MAX_ANGLE - MIN_ANGLE);
const toValue = (angle: number) => {
const raw = ((angle - MIN_ANGLE) / (MAX_ANGLE - MIN_ANGLE)) * (max - min);
return clamp(min + Math.round(raw / step) * step, min, max);
};
function handlePointerDown(e: PointerEvent<HTMLDivElement>) {
if (e.pointerType === 'mouse' && e.button !== 0) return;
// Keep sending events to this element until release, even if the pointer leaves the knob
e.currentTarget.setPointerCapture(e.pointerId);
drag.current = {
pointerId: e.pointerId,
lastAngle: pointerAngle(e.currentTarget, e.clientX, e.clientY),
rotation: toAngle(value),
};
}
function handlePointerMove(e: PointerEvent<HTMLDivElement>) {
const d = drag.current;
if (!d || d.pointerId !== e.pointerId) return;
const angle = pointerAngle(e.currentTarget, e.clientX, e.clientY);
let delta = angle - d.lastAngle;
// When crossing the bottom (the 180 / -180 boundary), don't treat it as a large difference in the opposite direction
if (delta > 180) delta -= 360;
if (delta < -180) delta += 360;
d.lastAngle = angle;
d.rotation = clamp(d.rotation + delta, MIN_ANGLE, MAX_ANGLE);
const next = toValue(d.rotation);
if (next !== value) onChange(next);
}
function handlePointerEnd(e: PointerEvent<HTMLDivElement>) {
if (drag.current?.pointerId === e.pointerId) drag.current = null;
}
function handleKeyDown(e: KeyboardEvent<HTMLDivElement>) {
const keys: Record<string, number> = {
ArrowRight: value + step,
ArrowUp: value + step,
ArrowLeft: value - step,
ArrowDown: value - step,
PageUp: value + step * 10,
PageDown: value - step * 10,
Home: min,
End: max,
};
if (!(e.key in keys)) return;
e.preventDefault(); // Keep arrow keys etc. from scrolling the page
onChange(clamp(keys[e.key], min, max));
}
const angle = toAngle(value);
return (
<div
className="knob"
role="slider"
tabIndex={0}
aria-label={label}
aria-valuemin={min}
aria-valuemax={max}
aria-valuenow={value}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerEnd}
onPointerCancel={handlePointerEnd}
onKeyDown={handleKeyDown}
>
<svg viewBox="0 0 160 160" aria-hidden="true">
{/* Scale arc. Set pathLength to 360 so the angle is used directly as the length */}
<circle className="knob-track" cx="80" cy="80" r="72" pathLength={360}
strokeDasharray="270 360" transform="rotate(135 80 80)" />
<circle className="knob-fill" cx="80" cy="80" r="72" pathLength={360}
strokeDasharray={`${angle - MIN_ANGLE} 360`} transform="rotate(135 80 80)" />
<g transform={`rotate(${angle} 80 80)`}>
<circle className="knob-body" cx="80" cy="80" r="56" />
<line className="knob-mark" x1="80" y1="34" x2="80" y2="52" />
</g>
</svg>
</div>
);
}
On the calling side, the value is held in state and passed down.
import { useState } from 'react';
import { Knob } from './Knob';
export function App() {
const [volume, setVolume] = useState(50);
return (
<main>
<Knob label="音量" value={volume} onChange={setVolume} />
<p className="value">音量 <output>{volume}</output></p>
</main>
);
}
Getting the pointer angle with Math.atan2
pointerAngle takes the horizontal difference dx and the vertical difference dy from the knob's center to the pointer, and returns the direction in degrees. Math.atan2(y, x) is a function that returns an angle in radians in the range -π to π, measured from the positive x-axis (to the right on screen) as 0. The code converts it to degrees with * 180 / Math.PI.
Here the arguments are swapped to Math.atan2(dx, -dy). With this, straight up is 0 degrees, right is 90 degrees, and left is -90 degrees, so the numbers increase clockwise. Straight down is the boundary between 180 and -180 degrees. Screen y coordinates grow as you move downward, so the sign of dy is flipped.
toAngle and toValue convert between the knob's angle and the value. -135 degrees corresponds to min, and 135 degrees corresponds to max. toValue rounds to a multiple of step, so setting step to 5 makes the value move in steps of 5. (In my tests I only tried step set to 1.)
Adding up the delta from the last event so the value doesn't jump past the bottom
handlePointerMove does not use the pointer's direction directly. Instead, it adds delta, the difference from the previous pointermove, to the knob's angle rotation. After adding, it clamps the result to the range -135 to 135 degrees.
For comparison, I also made two other versions.
- A version that clamps the pointer's direction to -135 to 135 degrees and uses it directly as the knob's angle
- A version that adds the delta but has no correction for crossing the bottom (the two lines that add or subtract 360 from
delta)
For each of the three versions, I grabbed the knob at straight up (0 degrees), at 60px from the center, and traced clockwise in 5-degree steps up to 225 degrees (lower left). After that, I moved back to the 135-degree position.
--- Final version (adds the difference) ---
真上でつかむ: 50
時計回り: 45度→67 90度→83 135度→100 170度→100 180度→100 185度→100 190度→100 225度→100
戻す: 180度→83 135度→67
値 50 のまま、右でつかんで 1px 動かす: 50
--- Version that uses the direction as-is ---
真上でつかむ: 50
時計回り: 45度→67 90度→83 135度→100 170度→100 180度→100 185度→0 190度→0 225度→0
戻す: 180度→100 135度→100
値 50 のまま、右でつかんで 1px 動かす: 84
--- Version with no correction directly below ---
真上でつかむ: 50
時計回り: 45度→67 90度→83 135度→100 170度→100 180度→100 185度→0 190度→2 225度→15
戻す: 180度→100 135度→83
値 50 のまま、右でつかんで 1px 動かす: 50
Look at the 185度 entry in the clockwise line. In the version that uses the pointer's direction directly, the value jumped from 100 to 0 as soon as the pointer passed straight down and reached 185 degrees. This happened because the Math.atan2 result switched from 180 degrees to -175 degrees, and clamping that to -135 degrees put the knob at the far left.
In the version without the correction, a single step from 180 degrees to 185 degrees counted as a change of -355 degrees. The knob swung all the way to the left end and became 0, and the later movement increased it to 2 and then 15. When delta is larger than 180 degrees, subtracting 360 fixes it. When delta is smaller than -180 degrees, adding 360 fixes it. This turns the large jump back into the small difference in the actual direction.
In the finished version, the value stayed at 100 after reaching 100 at the 135-degree position, even when the pointer crossed straight down. Turning back, the value began to drop right away (67 at 135 degrees). This is because the version does not keep any amount turned beyond the range in rotation. It clamps to -135 to 135 degrees every time.
The last line of each version is the result of grabbing the knob with a value of 50 on the right (90 degrees) and moving it by only 1px. In the version that uses the pointer's direction directly, the value jumped to 84 to match the direction at the grab point. In the two versions that add the delta, grabbing alone does not change the value.
This correction has a flip side. If the pointer turns past 180 degrees between two pointermove events, it is treated as a movement in the opposite direction. In the finished version, I grabbed the top of a knob with a value of 50 and moved it in a single pointermove, without passing through the intermediate positions.
--- Final version: moves a large amount in one pointermove ---
値 50 で真上をつかみ、1回で時計回りに 170 度の位置へ: 100
値 50 で真上をつかみ、1回で時計回りに 190 度の位置へ: 0
Moving clockwise to the 170-degree position gave the maximum, 100. Moving to the 190-degree position was treated as a 170-degree counterclockwise turn, and the value became 0.
The add-the-delta approach assumes that the angle the pointer turns between one pointermove and the next is less than 180 degrees. Tracing close to the center of the knob makes the direction change a lot with a small move, so this assumption breaks easily.
Keeping the drag going after the pointer leaves the knob
handlePointerDown calls setPointerCapture. With this, the knob keeps receiving pointermove events even if the pointer moves outside it, until the button or finger is released.
The knob is 160×160px. I grabbed it on the right (90 degrees), moved the pointer outward to 150px from the center, and traced clockwise to straight down (180 degrees) while staying at that distance. The value changed as follows. All the traced points stayed inside the display area.
--- Final version: rotates even when moved far outside the knob ---
右のまま半径 150px まで外へ出たあとの値: 50
半径 150px で時計回り: 135度→67 180度→83
180 度・半径 150px の点: (180, 246)/表示領域 360×320
つまみの大きさ: 160×160px
The value went 50, 67, 83 for each 45 degrees turned. This is the same increase as when I traced at a radius of 60px (67 at 45 degrees from straight up, 83 at 90 degrees). Only the direction decides the value, so the farther from the center you trace, the more the mouse has to move to turn the same angle.
Setting touch-action: none for finger dragging
In the CSS, the knob has touch-action: none.
.knob {
display: inline-block;
width: 160px;
height: 160px;
border-radius: 50%;
cursor: grab;
/* Keep the page from scrolling when dragging with a finger */
touch-action: none;
user-select: none;
}
This setting stops the browser from scrolling or zooming when you trace over the knob with a finger, so that all the movement is delivered to the page as pointermove. A dial is traced both vertically and horizontally, so you cannot leave only the vertical part to the browser as you would with a swipe.
I changed only the knob's touch-action to auto, traced 90 degrees clockwise from straight up with a finger, and compared the two.
touch-action: none: 真上から時計回りに 90 度なぞる: 値 83 / scrollY 0 / イベント: pointerdown pointerup
touch-action: auto: 真上から時計回りに 90 度なぞる: 値 56 / scrollY 0 / イベント: pointerdown pointercancel
With auto, pointercancel arrived right after the trace began, and the value stopped at 56. The browser had started treating the finger movement as a scroll or zoom gesture. In both cases scrollY is 0 because the page was already at the top, so the finger could not scroll it any further up when moved down. What the comparison shows is whether pointercancel arrived and the difference in value. With none, pointerup arrived at the end, and the value was 83, the same as with the mouse.
Making it work with the keyboard
Dragging alone would leave people who cannot use a mouse or finger unable to change the value. So the knob element has role="slider" and tabIndex={0} so it can receive focus, and onKeyDown changes the value for each key.
The key assignments follow the slider pattern in the WAI-ARIA Authoring Practices Guide. The right and up arrows increase the value by one step, and the left and down arrows decrease it by one step. Home and End move to the minimum and maximum. The APG lists Page Up and Page Down as optional keys for larger moves than one step. Here they move the value by 10. The current value goes in aria-valuenow, and the range goes in aria-valuemin and aria-valuemax.
I pressed keys in sequence and checked the aria-valuenow value.
--- Final version: keyboard ---
Home→0 ArrowUp→1 ArrowRight→2 ArrowDown→1 PageUp→11 PageUp→21 End→100 ArrowUp→100 PageDown→90 ArrowLeft→89
表示: 音量 89
属性: role=slider aria-label=音量 aria-valuemin=0 aria-valuemax=100
After End set the value to 100, pressing the up arrow kept it at 100. For keys that are handled, e.preventDefault() is called so that the browser's default actions, such as scrolling the page, do not happen.
Drawing the scale arc in degrees with pathLength
The arc around the knob is made of two <circle> elements of the same size on top of each other. The bottom one is gray and covers the full 270 degrees. The top one is light blue and covers the current value.
pathLength is set to 360 so the circle's stroke length can be handled as an angle. With this, "270 360" in stroke-dasharray means "draw 270 degrees' worth and leave the rest undrawn." In the SVG specification, the circle's stroke starts at the 3 o'clock position and goes clockwise. So the circle is rotated with rotate(135 80 80) so that drawing starts at the lower left (-135 degrees).
The knob body and the indicator line are grouped in a <g>, which is rotated around the center with rotate(${angle} 80 80). The whole SVG has aria-hidden="true", which removes the graphic from the accessibility tree. The value is conveyed by the knob element's aria-valuenow.





