When to use it#
- Use a slider for an approximate value over a small range with a coarse step, where seeing the position helps: a search distance, a volume.
- Put it in a Field, after the label, with the ends of the range in the help text. Give
valueTextthe unit, so a screen reader (software that reads the screen aloud) says “15 km”, not “15”. - Not for an exact value, such as an amount or an age: use a NumberInput. A slider is never the only way to enter a number that matters: put a NumberInput beside it.
Example#
From 1 to 20 km.
import { Field, Slider } from '@kvirn-ui/react'
import { useSliderTexts } from './texts.ts'
export function DefaultSlider() {
const { texts } = useSliderTexts()
return (
<Field.Root>
<Field.Label marker="none">{texts.distanceLabel}</Field.Label>
<Slider
name="distance"
min={1}
max={20}
defaultValue={1}
valueText={(km) => `${km} ${texts.distanceUnit}`}
/>
<Field.HelpText>{texts.distanceEnds}</Field.HelpText>
</Field.Root>
)
}Use cases#
A search distance in a plain form
Use it when the form needs only the number. Without value the browser keeps the number, and sending the form posts it under the slider’s name. A form reset puts back defaultValue.
import { Button, Field, Slider } from '@kvirn-ui/react'
import { useState } from 'react'
import { useSliderTexts } from './texts.ts'
export function PlainForm() {
const { texts } = useSliderTexts()
const [sent, setSent] = useState<string | undefined>()
return (
<form
onSubmit={(event) => {
event.preventDefault()
const distance = new FormData(event.currentTarget).get('distance')
setSent(typeof distance === 'string' ? distance : undefined)
}}
>
<Field.Root>
<Field.Label marker="none">{texts.distanceLabel}</Field.Label>
<Slider
name="distance"
min={1}
max={20}
defaultValue={1}
valueText={(km) => `${km} ${texts.distanceUnit}`}
/>
<Field.HelpText>{texts.distanceEnds}</Field.HelpText>
</Field.Root>
<Button type="submit" className="kv-button--primary">
{texts.send}
</Button>
{sent === undefined ? null : (
<p>
{texts.sent} {sent}
</p>
)}
</form>
)
}Props in this example:
nameon SliderdefaultValueon SlidervalueTexton Slider
A search distance with an exact box beside it
Dragging is hard for some people and imprecise for everyone, so give an exact way in: the slider for a rough choice, the number box for the exact distance. In the example the two stay in step.
From 1 to 20 km. You can also type a number.
import { Field, InputGroup, NumberInput, Slider } from '@kvirn-ui/react'
import { useId, useState } from 'react'
import { useSliderTexts } from './texts.ts'
export function WithNumberInput() {
const { texts } = useSliderTexts()
const labelId = useId()
const hintId = useId()
const [distance, setDistance] = useState('1')
const [sliderValue, setSliderValue] = useState(1)
const isOutOfRange = distance !== '' && (Number(distance) < 1 || Number(distance) > 20)
return (
<Field.Root invalid={isOutOfRange}>
<Field.Label marker="none">
<span id={labelId}>{texts.distanceLabel}</span>
</Field.Label>
<Slider
aria-labelledby={labelId}
aria-describedby={hintId}
min={1}
max={20}
value={sliderValue}
onValueChange={(value) => {
setSliderValue(value)
setDistance(String(value))
}}
valueText={(km) => `${km} ${texts.distanceUnit}`}
/>
<InputGroup.Root>
<NumberInput
name="distance"
className="kv-input--width-4"
value={distance}
onValueChange={(next) => {
setDistance(next)
const parsed = Number(next)
if (next.trim() !== '' && Number.isFinite(parsed)) {
setSliderValue(Math.min(20, Math.max(1, parsed)))
}
}}
/>
<InputGroup.Addon>{texts.distanceUnit}</InputGroup.Addon>
</InputGroup.Root>
<Field.HelpText>
<span id={hintId}>{texts.distanceHint}</span>
</Field.HelpText>
<Field.ErrorMessage>{texts.distanceOutOfRange}</Field.ErrorMessage>
</Field.Root>
)
}Props in this example:
valueon SlideronValueChangeon Slideraria-labelledbyon Slider
Information: Implement like this
Let the NumberInput own the Field. A click on the label then moves focus to the number box, and the error belongs to it. Name and describe the slider with aria-labelledby and aria-describedby, pointing at a span with an id inside the label and the help text. Give only the NumberInput a name, so the form sends the value once.
Recycling points that update as the distance changes
A list that changes while the thumb moves is a status message. The slider announces only its own value, so say the new count yourself, once, after the person stops. The example does this half a second after the last change, politely: the screen reader finishes what it is saying first.
From 1 to 20 km.
2 recycling points within 5 km
- Harbour recycling centre, 2 km
- Hill Road collection point, 4 km
import { Field, Slider, Stack, useAnnouncer } from '@kvirn-ui/react'
import { useEffect, useState } from 'react'
import { useSliderTexts } from './texts.ts'
export function LiveResults() {
const { texts } = useSliderTexts()
const { announce } = useAnnouncer()
const [distance, setDistance] = useState(5)
const [hasMoved, setHasMoved] = useState(false)
const nearby = texts.stations.filter((station) => station.distance <= distance)
const message = texts.results(nearby.length, distance)
useEffect(() => {
if (!hasMoved) {
return
}
// Wait until the thumb stops, so one move is one message.
const timer = setTimeout(() => announce(message), 500)
return () => clearTimeout(timer)
}, [announce, hasMoved, message])
return (
<Stack className="kv-stack--gap-4">
<Field.Root>
<Field.Label marker="none">{texts.distanceLabel}</Field.Label>
<Slider
min={1}
max={20}
value={distance}
onValueChange={(value) => {
setDistance(value)
setHasMoved(true)
}}
valueText={(km) => `${km} ${texts.distanceUnit}`}
/>
<Field.HelpText>{texts.distanceEnds}</Field.HelpText>
</Field.Root>
<p>{message}</p>
<ul>
{nearby.map((station) => (
<li key={station.name}>
{station.name}, {station.distance} {texts.distanceUnit}
</li>
))}
</ul>
</Stack>
)
}Props in this example:
valueon SlideronValueChangeon SlidervalueTexton Slider
Warning: Don't forget
Announce the result with the Announcer, once and after a pause, never on every step (4.1.3 Status Messages, level AA). Don’t move focus or leave the page when the value changes (3.2.2 On Input, level A).
A distance that is off for now
When another choice makes the slider meaningless, disable it and say why in the help text. Here disabled is set on the Field, which disables the slider too, and Tab skips it.
From 1 to 20 km.
import { Checkbox, Field, Slider, Stack } from '@kvirn-ui/react'
import { useState } from 'react'
import { useSliderTexts } from './texts.ts'
export function NotAvailable() {
const { texts } = useSliderTexts()
const [isWholeMunicipality, setIsWholeMunicipality] = useState(false)
return (
<Stack className="kv-stack--gap-4">
<Field.Root>
<Checkbox
checked={isWholeMunicipality}
onCheckedChange={(checked) => setIsWholeMunicipality(checked)}
/>
<Field.Label marker="none">{texts.wholeMunicipality}</Field.Label>
</Field.Root>
<Field.Root disabled={isWholeMunicipality}>
<Field.Label marker="none">{texts.distanceLabel}</Field.Label>
<Slider
name="distance"
min={1}
max={20}
defaultValue={5}
valueText={(km) => `${km} ${texts.distanceUnit}`}
/>
<Field.HelpText>
{isWholeMunicipality ? texts.distanceOff : texts.distanceEnds}
</Field.HelpText>
</Field.Root>
</Stack>
)
}Props in this example:
defaultValueon Slider
Accessibility#
What it does for you#
- APG pattern: Slider, single thumb. The native form:
<input type="range">, whose implicit role issliderand whosearia-valuemin,aria-valuemaxandaria-valuenoware native. - Deviations: none from APG.
- Native elements used:
<input type="range">, named by a<label for>(Field.Label) or byaria-labelledby.
A Slider is for an approximate value (a search radius, a volume). It is never the only way to enter a number that matters: an exact value is a NumberInput, and a slider beside one gives a resident both. It is a native input, so the browser supplies every key, the drag, a press on the track, form submission, form.reset() and disabled. Slider adds the Field's wiring, aria-valuetext, the part class and data-* state. It holds no form state: pass value and onValueChange, or defaultValue and name for a plain form.
| Part | Element / role | ARIA / state | Notes |
|---|---|---|---|
| Slider | <input type="range">, implicit slider | Native value, min and max. aria-valuetext always. id, aria-describedby (help text, then the error) and aria-invalid="true" from the Field. Native disabled. data-invalid, data-disabled, data-focus-visible | Class kv-slider. Props: value, defaultValue, min (0), max (100), step (1), name, disabled, onValueChange(value, { reason: 'input', event }), valueText, aria-labelledby, native input props except type, role, required |
| Field.Label | <label for>, the slider's name | The name never changes with the value | A Slider that owns the Field, or a plain Field. A Slider beside a NumberInput: see the rules below |
useSlider | the same attributes, for your own elements | inputProps, isInvalid, isDisabled, isFocusVisible, value, valueText | Spread inputProps on your <input> |
Rules, each with an automated test:
- A native range.
type="range", classkv-slider, noroleand noaria-valuenowwritten by the component, noaria-required. aria-valuetextis always set. It isvalueText(value), or the number formatted with the provider's locale. It follows the value, controlled or not. Say the unit invalueText(15 km).- Named by its label. In a Field the label's
formatches the input'sid. The help text describes it. - A Slider beside a NumberInput. An explicit
aria-labelledbyopts the Slider out of the Field: it gets noid, noaria-describedby, noaria-invalidand nodata-invalidfrom it. The NumberInput owns the Field's id, the label'sforand the error. The Field's label and help text take noid, so wrap their text in a<span id>and pointaria-labelledbyandaria-describedbyat it. Passaria-describedbyyourself for the help text. A disabled Field still disables the Slider. - Controlled and uncontrolled.
valueis anumber;onValueChangegetsNumber(event.currentTarget.value). A form submit sendsname=valueas a string;form.reset()restoresdefaultValue. - Disabled. A Field's
disabledor the prop gives nativedisabledanddata-disabled. - Dev warnings (once): a Slider in a Field with no Field.Label; a Slider outside a Field with no accessible name (
aria-labeloraria-labelledbycount); anidinside a Field; aminthat is not belowmax; avalueordefaultValueoutside the range.
It announces nothing.
What you need to do#
- Name the quantity and its unit in the label ("Distance in kilometres"); never a label that changes with the value.
- Say the unit in
valueText("15 km", "40 percent"): a bare number is right only when it has no unit. - State the ends of the range in the help text. Never "Drag the slider" as the only instruction.
- Never the only way in for an exact number: pair it with a NumberInput beside it, where the NumberInput owns the Field and the Slider has
aria-labelledby. A value with legal effect is a NumberInput alone. This is a KvirnUI rule for precision and for touch users without keys, not a WCAG requirement: dragging a native range is excepted from 2.5.7 Dragging Movements (AA), and its keys meet 2.1.1 Keyboard (A). - Results that update as the value moves are announced once, debounced, through the
Announcer(4.1.3 Status Messages, AA), never per step. This is your code: the Slider announces nothing itself. - Updating results on input is fine, but never navigate or move focus on change (3.2.2 On Input, A).
- A not-available slider is
disabled, with the reason in the help text.
Warning: Don't forget
Name the quantity and its unit in the label, and give valueText the unit. Without a name a screen reader user hears only “slider” and can’t tell what it is for (4.1.2 Name, Role, Value). Without the unit they hear a bare number.
Visual and modes#
- Focus indicator: a ring around the input box with at least 3:1 contrast against the colours next to it (2.4.7 Focus Visible, AA; 2.4.13 Focus Appearance, AAA).
- Target size: the box is tall enough to press, and the thumb is at least 24px (2.5.8 Target Size (Minimum), AA). On a coarse pointer, such as a finger, the thumb's hit area is larger.
- Colour: the thumb and the track edge each have at least 3:1 contrast against their background (1.4.11 Non-text Contrast, AA). An invalid slider has a heavier error-coloured edge plus the message. A disabled slider has a dashed edge and a muted thumb.
- Forced colours (the system's own colour scheme): the track uses the system field colour with a button-border edge, the thumb uses the system highlight colour, a disabled slider is grey, and an invalid one has a heavier edge in the system text colour. The forced-colours sweep runs every story and checks the boundaries and the focus ring; the thumb and track colours themselves are checked by eye.
- Reduced motion: the track's border colour changes gradually only when the person has not asked for reduced motion. The thumb never animates.
- Right-to-left (RTL) pages: the browser reverses the range, and nothing in the theme depends on direction.
Warning: Don't forget
If you restyle the slider, keep the thumb and the track edge at least 3:1 against their background (1.4.11 Non-text Contrast). Keep the thumb at least 24 pixels across (2.5.8 Target Size (Minimum)).
Focus management#
- Initial focus: not moved.
- Trap: no.
- Restore to: not applicable.
- Never obscured by: the focus ring is drawn on the input's box, outside the track, and nothing around clips it (2.4.11 Focus Not Obscured (Minimum), AA; 2.4.13 Focus Appearance, AAA). Consumers with a sticky header set
scroll-padding.
WCAG success criteria#
- 1.3.1 Info and Relationships (A), 4.1.2 Name, Role, Value (A): native range, label
for,aria-valuetext. - 1.4.11 Non-text Contrast (AA): the track edge, the thumb and the focus ring.
- 1.4.10 Reflow (AA), 1.4.12 Text Spacing (AA): full width, the label wraps.
- 2.1.1 Keyboard (A), 2.4.3 Focus Order (A): native Tab and the range keys.
- 2.4.7 Focus Visible (AA), 2.4.11 Focus Not Obscured (Minimum) (AA), 2.4.13 Focus Appearance (AAA, not counted toward the AA bar).
- 2.5.7 Dragging Movements (AA): dragging a native range is the user agent's own, unmodified behaviour, which the criterion excepts. The alternative is the keys, and, with a NumberInput beside it, that box.
- 2.5.8 Target Size (Minimum) (AA): the box and the thumb.
- 3.2.2 On Input (A): a slider never changes context.
- 3.3.1 Error Identification (A), 3.3.2 Labels or Instructions (A): the Field's error and help text.
Keyboard#
- Focus
- native
- Selection follows focus
- n/a
- Arrows wrap
- no
- Shortcuts
- none
Each slider is one Tab stop. Nothing is intercepted: every key keeps its native behaviour.
| Key | Where | What happens |
|---|---|---|
| Tab | before the slider | Moves focus to the slider. One Tab stop Test: slider.test.tsx › Tab moves to the slider, one stop |
| Shift+Tab | on the slider | Moves focus to the previous focusable element Test: slider.test.tsx › Shift+Tab moves to the previous focusable element |
| Tab | disabled slider | Skips it (native disabled leaves the Tab sequence)Test: slider.test.tsx › Tab skips a disabled slider |
| ArrowRight / ArrowUp | on the slider | Increases by stepTest: slider.test.tsx › ArrowRight and ArrowUp increase by one step |
| ArrowLeft / ArrowDown | on the slider | Decreases by stepTest: slider.test.tsx › ArrowLeft and ArrowDown decrease by one step |
| Home | on the slider | Sets minTest: slider.test.tsx › Home sets the minimum |
| End | on the slider | Sets maxTest: slider.test.tsx › End sets the maximum |
| PageUp | on the slider | Increases by a larger step (a step the browser sets) Test: slider.test.tsx › PageUp and PageDown move by a larger step |
| PageDown | on the slider | Decreases by a larger step (a step the browser sets) Test: slider.test.tsx › PageUp and PageDown move by a larger step |
| ArrowLeft / ArrowRight | right-to-left page | The browser reverses them: Left increases, Right decreases Test: slider.test.tsx › in a right-to-left page the arrows are reversed |
Arrows stop at min and max. The value is announced natively; there is no live region.
API reference#
import { Field, Slider, useSlider } from '@kvirn-ui/react'Slider
Renders <input type="range">. It takes every attribute of an <input> except type, role, required and readOnly (a range always has a value), and passes ref to it. Put it in a Field.Root, after the Field.Label. The label, help text and error are the Field’s parts, and the slider has no strings of its own. The default theme is described on Theming.
| Prop | Type | Default | Description |
|---|---|---|---|
value | number | – | Controlled: the number from your form logic. Pair it with onValueChange. The slider never copies it into state of its own. |
defaultValue | number | halfway | Uncontrolled: the browser keeps the number, and a form submit sends it. |
min | number | 0 | The lowest value. |
max | number | 100 | The highest value. |
step | number | 1 | The distance between values. |
name | string | – | The name a form submit uses. |
disabled | boolean | false | Native disabled: skipped by Tab. A disabled Field disables the slider too. |
valueText | (value: number) => string | the number in the provider’s locale | What aria-valuetext says. Give it the unit, such as “15 km”, or a screen reader says only the number. |
onValueChange | (value: number, details: SliderChangeDetails) => void | – | Called on every change with the new number and { reason: "input", event }. It only reports. onChange still works too. |
aria-labelledby | string | – | Names the slider by another element, and opts it out of its Field: no id, description or invalid state from it. For a slider beside a NumberInput that owns the Field. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-slider | always | The part class. The default theme styles it. |
aria-valuetext | always | From valueText, or the number in the provider’s locale. |
aria-describedby | ids | From the Field: the help text, then the error, then your own ids. With aria-labelledby the Field adds none, and only your own ids are used. |
data-invalid | present or absent | The Field is invalid. |
data-disabled | present or absent | The Field or the disabled prop disables it. |
data-focus-visible | present or absent | The slider has keyboard focus (:focus-visible). |
aria-invalid | "true" or absent | Set when its Field is invalid. |
useSlider
Options
| Prop | Type | Default | Description |
|---|---|---|---|
value | number | – | Controlled: the number from your logic. |
defaultValue | number | halfway | Uncontrolled: the browser keeps the number. |
min | number | 0 | The lowest value. |
max | number | 100 | The highest value. |
step | number | 1 | The distance between values. |
name | string | – | The name a form submit uses. |
disabled | boolean | false | Native disabled. |
onValueChange | (value: number, details: SliderChangeDetails) => void | – | Called with the new number on every change. It only reports. |
valueText | (value: number) => string | the number in the provider’s locale | What aria-valuetext says. |
aria-labelledby | string | – | Names the slider by another element and opts it out of its Field. |
Result
| Prop | Type | Default | Description |
|---|---|---|---|
inputProps | SliderPartProps | – | Spread on an <input>: class, type, range, Field wiring, aria-valuetext, state attributes and handlers. |
isInvalid | boolean | – | Whether the Field is invalid. |
isDisabled | boolean | – | Whether the slider is disabled. |
isFocusVisible | boolean | – | Whether the slider has keyboard (:focus-visible) focus. |
value | number | – | The current number. |
valueText | string | – | What aria-valuetext says. |
Known issues#
- The thumb and track colours are checked by eye. They are parts the browser draws itself, styled separately for each browser engine, so the automated forced-colours check covers the boundaries and the focus ring but not these. Check them in Windows Contrast Themes yourself.
- A value between steps. The browser snaps the thumb to the nearest step; beside a NumberInput, the NumberInput keeps the typed number.
form.reset()andaria-valuetext. For an uncontrolled slider the text follows the native value after each change and after a form reset.- A controlled
valueoff the step or outside the range. The browser snaps the thumb andaria-valuenow, butaria-valuetextis built from thevalueyou passed, so the two can disagree. Pass a value on a step and insideminandmax.
Information: Did you know?
If an issue here affects your service, list it in your accessibility statement with its workaround.
Testing#
The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.
| AT + browser + OS | Agent check | Human check | Result | Notes |
|---|---|---|---|---|
| Automated (re-runnable tests) | ||||
| axe, WCAG 2.2 A and AA, every story, 4 themes | pass | n/a | pass | slider.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | slider.test.tsx › valueText sets aria-valuetext, and it follows each change; expectNoA11yViolations |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 10 rows, each names a test (slider.test.tsx › Tab moves to the slider, one stop) |
| Focus order and management | pass | n/a | pass | slider.test.tsx asserts focus (toHaveFocus); first rule: Tab moves to the slider, one stop |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | pass | n/a | pass | the four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI |
| Core (required for beta) | ||||
| NVDA + Chrome + Windows | pending | pending | pending | |
| VoiceOver + Safari + iOS | pending | pending | pending | |
| Release (before 1.0 and each minor) | ||||
| JAWS + Chrome + Windows | pending | pending | pending | |
| TalkBack + Chrome + Android | pending | pending | pending | |
| VoiceOver + Safari + macOS | pending | pending | pending |
What to check#
- Tab to the slider: you hear the label, "slider", the value with its unit and the help text.
- Press Right or Up, then Left or Down: the value moves one step each time and the new value is spoken with its unit.
- Press Home and End: the value jumps to the ends. Press Page Up and Page Down: it jumps by a larger step.
- With a NumberInput beside it, type a number: the slider moves. Click the label: the number box is focused.
- Disable the Field: Tab skips the slider and the help text says why.
- On a phone with a screen reader, change the value without dragging: the value text is spoken, and the NumberInput works.