Accessible, CSS-agnostic slider component for React applications
npx @tessl/cli install tessl/npm-react-slider@2.0.00
# React Slider
1
2
React Slider is an accessible, CSS-agnostic slider component for React applications. It provides both single and multi-handle sliders with extensive customization options, accessibility features, keyboard navigation, and comprehensive event handling for user interactions.
3
4
## Package Information
5
6
- **Package Name**: react-slider
7
- **Package Type**: npm
8
- **Language**: JavaScript (React)
9
- **Installation**: `npm install react-slider`
10
11
## Core Imports
12
13
```javascript
14
import ReactSlider from "react-slider";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const ReactSlider = require("react-slider");
21
```
22
23
## Basic Usage
24
25
```javascript
26
import React, { useState } from "react";
27
import ReactSlider from "react-slider";
28
29
// Single value slider
30
function SingleSlider() {
31
const [value, setValue] = useState(50);
32
33
return (
34
<ReactSlider
35
value={value}
36
onChange={setValue}
37
min={0}
38
max={100}
39
step={1}
40
/>
41
);
42
}
43
44
// Multi-value slider
45
function MultiSlider() {
46
const [values, setValues] = useState([20, 80]);
47
48
return (
49
<ReactSlider
50
value={values}
51
onChange={setValues}
52
min={0}
53
max={100}
54
minDistance={10}
55
/>
56
);
57
}
58
59
// Custom styled slider
60
function StyledSlider() {
61
return (
62
<ReactSlider
63
className="horizontal-slider"
64
thumbClassName="slider-thumb"
65
trackClassName="slider-track"
66
defaultValue={[20, 80]}
67
ariaLabel={["Lower thumb", "Upper thumb"]}
68
renderThumb={(props, state) => (
69
<div {...props}>
70
{state.valueNow}
71
</div>
72
)}
73
/>
74
);
75
}
76
```
77
78
## Architecture
79
80
React Slider is built around several key concepts:
81
82
- **Component Props**: Extensive configuration through props covering values, behavior, styling, and accessibility
83
- **Event System**: Comprehensive event handlers for before/during/after value changes
84
- **Custom Rendering**: Render prop pattern for customizing thumbs, tracks, and marks
85
- **Accessibility**: Full ARIA support with keyboard navigation and screen reader compatibility
86
- **Responsive Design**: Built-in ResizeObserver integration for dynamic sizing
87
88
## Capabilities
89
90
### ReactSlider Component
91
92
The main slider component providing single and multi-thumb functionality with extensive customization options.
93
94
```javascript { .api }
95
/**
96
* Accessible, CSS-agnostic slider component for React
97
* @param props - ReactSlider configuration props
98
* @returns JSX.Element - Rendered slider component
99
*/
100
function ReactSlider(props: ReactSliderProps): JSX.Element;
101
102
interface ReactSliderProps {
103
// Core value props
104
min?: number;
105
max?: number;
106
step?: number;
107
defaultValue?: number | number[];
108
value?: number | number[];
109
minDistance?: number;
110
111
// Behavior props
112
pageFn?: (step: number) => number;
113
orientation?: 'horizontal' | 'vertical';
114
disabled?: boolean;
115
snapDragDisabled?: boolean;
116
invert?: boolean;
117
pearling?: boolean;
118
withTracks?: boolean;
119
marks?: boolean | number | number[];
120
121
// Styling props
122
className?: string;
123
thumbClassName?: string;
124
thumbActiveClassName?: string;
125
trackClassName?: string;
126
markClassName?: string;
127
128
// Event handler props
129
onBeforeChange?: (value: number | number[], thumbIndex: number) => void;
130
onChange?: (value: number | number[], thumbIndex: number) => void;
131
onAfterChange?: (value: number | number[], thumbIndex: number) => void;
132
onSliderClick?: (value: number) => void;
133
134
// Accessibility props
135
ariaLabel?: string | string[];
136
ariaLabelledby?: string | string[];
137
ariaValuetext?: string | ((state: ThumbState) => string);
138
139
// Custom render props
140
renderThumb?: (props: ThumbProps, state: ThumbState) => React.ReactElement;
141
renderTrack?: (props: TrackProps, state: TrackState) => React.ReactElement;
142
renderMark?: (props: MarkProps) => React.ReactElement;
143
}
144
145
interface ThumbState {
146
index: number;
147
value: number | number[];
148
valueNow: number;
149
}
150
151
interface TrackState {
152
index: number;
153
value: number | number[];
154
}
155
156
interface ThumbProps {
157
key: string;
158
className: string;
159
style: React.CSSProperties;
160
onMouseDown: (e: React.MouseEvent) => void;
161
onTouchStart: (e: React.TouchEvent) => void;
162
onFocus: (e: React.FocusEvent) => void;
163
tabIndex: number;
164
role: string;
165
'aria-orientation': string;
166
'aria-valuenow': number;
167
'aria-valuemin': number;
168
'aria-valuemax': number;
169
'aria-label'?: string;
170
'aria-labelledby'?: string;
171
'aria-disabled': boolean;
172
'aria-valuetext'?: string;
173
}
174
175
interface TrackProps {
176
key: string;
177
className: string;
178
style: React.CSSProperties;
179
}
180
181
interface MarkProps {
182
key: string | number;
183
className: string;
184
style: React.CSSProperties;
185
}
186
```
187
188
### Core Value Configuration
189
190
Configuration of slider values, constraints, and step behavior.
191
192
```javascript { .api }
193
// Value range configuration
194
min?: number; // Minimum slider value (default: 0)
195
max?: number; // Maximum slider value (default: 100)
196
step?: number; // Value increment/decrement step (default: 1)
197
198
// Initial and controlled values
199
defaultValue?: number | number[]; // Initial value for uncontrolled mode (default: 0)
200
value?: number | number[]; // Current value for controlled mode
201
202
// Multi-thumb constraints
203
minDistance?: number; // Minimum distance between thumbs (default: 0)
204
```
205
206
**Usage Examples:**
207
208
```javascript
209
// Single value slider with custom range
210
<ReactSlider
211
min={-100}
212
max={100}
213
step={5}
214
defaultValue={0}
215
/>
216
217
// Multi-value slider with constraints
218
<ReactSlider
219
min={0}
220
max={1000}
221
step={10}
222
defaultValue={[200, 800]}
223
minDistance={50}
224
/>
225
226
// Controlled slider
227
function ControlledSlider() {
228
const [value, setValue] = useState(25);
229
return (
230
<ReactSlider
231
value={value}
232
onChange={setValue}
233
min={0}
234
max={100}
235
/>
236
);
237
}
238
```
239
240
### Behavior Configuration
241
242
Configuration of slider interaction behavior and advanced features.
243
244
```javascript { .api }
245
// Navigation and interaction
246
pageFn?: (step: number) => number; // Custom Page Up/Down step calculation
247
orientation?: 'horizontal' | 'vertical'; // Slider orientation (default: 'horizontal')
248
disabled?: boolean; // Disable all interactions (default: false)
249
snapDragDisabled?: boolean; // Disable thumb snap on track click (default: false)
250
invert?: boolean; // Invert slider direction (default: false)
251
252
// Advanced behavior
253
pearling?: boolean; // Enable thumb pushing behavior (default: false)
254
withTracks?: boolean; // Render tracks between thumbs (default: true)
255
marks?: boolean | number | number[]; // Show marks on track (default: [])
256
```
257
258
**Usage Examples:**
259
260
```javascript
261
// Vertical slider with custom page function
262
<ReactSlider
263
orientation="vertical"
264
pageFn={(step) => step * 5}
265
defaultValue={50}
266
/>
267
268
// Inverted slider with pearling
269
<ReactSlider
270
invert={true}
271
pearling={true}
272
defaultValue={[30, 70]}
273
/>
274
275
// Slider with marks
276
<ReactSlider
277
marks={[0, 25, 50, 75, 100]}
278
defaultValue={50}
279
/>
280
281
// Slider with step-based marks
282
<ReactSlider
283
marks={10} // Shows marks at 0, 10, 20, 30, etc.
284
max={100}
285
step={5}
286
/>
287
```
288
289
### Event Handling
290
291
Comprehensive event system for tracking slider interactions and value changes.
292
293
```javascript { .api }
294
/**
295
* Called before starting to move a thumb (only if value will change)
296
* @param value - Initial value(s)
297
* @param thumbIndex - Index of the thumb being moved
298
*/
299
onBeforeChange?: (value: number | number[], thumbIndex: number) => void;
300
301
/**
302
* Called on every value change during interaction
303
* @param value - New value(s)
304
* @param thumbIndex - Index of the thumb being moved
305
*/
306
onChange?: (value: number | number[], thumbIndex: number) => void;
307
308
/**
309
* Called after moving a thumb has ended (only if value changed)
310
* @param value - Final value(s)
311
* @param thumbIndex - Index of the thumb that was moved
312
*/
313
onAfterChange?: (value: number | number[], thumbIndex: number) => void;
314
315
/**
316
* Called when the slider track is clicked
317
* @param value - Value at the clicked position
318
*/
319
onSliderClick?: (value: number) => void;
320
```
321
322
**Usage Examples:**
323
324
```javascript
325
function EventHandlerExample() {
326
const handleBeforeChange = (value, thumbIndex) => {
327
console.log('Starting to change:', value, 'thumb:', thumbIndex);
328
};
329
330
const handleChange = (value, thumbIndex) => {
331
console.log('Changing to:', value, 'thumb:', thumbIndex);
332
};
333
334
const handleAfterChange = (value, thumbIndex) => {
335
console.log('Final value:', value, 'thumb:', thumbIndex);
336
};
337
338
const handleSliderClick = (value) => {
339
console.log('Clicked at value:', value);
340
};
341
342
return (
343
<ReactSlider
344
onBeforeChange={handleBeforeChange}
345
onChange={handleChange}
346
onAfterChange={handleAfterChange}
347
onSliderClick={handleSliderClick}
348
defaultValue={[20, 80]}
349
/>
350
);
351
}
352
```
353
354
### Styling and CSS Classes
355
356
CSS class configuration for complete visual customization.
357
358
```javascript { .api }
359
// Main styling props
360
className?: string; // CSS class for slider container (default: 'slider')
361
thumbClassName?: string; // CSS class for thumb elements (default: 'thumb')
362
thumbActiveClassName?: string; // CSS class for active thumb (default: 'active')
363
trackClassName?: string; // CSS class for track elements (default: 'track')
364
markClassName?: string; // CSS class for mark elements (default: 'mark')
365
```
366
367
**Usage Examples:**
368
369
```javascript
370
// Custom CSS classes
371
<ReactSlider
372
className="my-slider"
373
thumbClassName="my-thumb"
374
thumbActiveClassName="my-active-thumb"
375
trackClassName="my-track"
376
markClassName="my-mark"
377
defaultValue={50}
378
/>
379
380
// Styled with CSS
381
/*
382
.my-slider {
383
width: 100%;
384
height: 20px;
385
background: #ddd;
386
border-radius: 10px;
387
}
388
389
.my-thumb {
390
width: 24px;
391
height: 24px;
392
background: #007bff;
393
border-radius: 50%;
394
border: 2px solid white;
395
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
396
}
397
398
.my-active-thumb {
399
background: #0056b3;
400
}
401
402
.my-track {
403
background: #007bff;
404
border-radius: 10px;
405
}
406
*/
407
```
408
409
### Accessibility Features
410
411
Complete accessibility support with ARIA attributes and keyboard navigation.
412
413
```javascript { .api }
414
// ARIA labeling
415
ariaLabel?: string | string[]; // ARIA label for thumbs
416
ariaLabelledby?: string | string[]; // ARIA labelledby for thumbs
417
ariaValuetext?: string | ((state: ThumbState) => string); // ARIA valuetext
418
419
interface ThumbState {
420
index: number; // Thumb index
421
value: number | number[]; // Current slider value(s)
422
valueNow: number; // Current thumb value
423
}
424
```
425
426
**Usage Examples:**
427
428
```javascript
429
// Accessibility labels
430
<ReactSlider
431
ariaLabel={["Minimum value", "Maximum value"]}
432
defaultValue={[20, 80]}
433
/>
434
435
// Dynamic aria-valuetext
436
<ReactSlider
437
ariaValuetext={(state) => `${state.valueNow}% completed`}
438
defaultValue={75}
439
/>
440
441
// Connected with external labels
442
<div>
443
<label id="temp-label">Temperature Range</label>
444
<ReactSlider
445
ariaLabelledby="temp-label"
446
min={-10}
447
max={40}
448
defaultValue={[18, 25]}
449
/>
450
</div>
451
```
452
453
### Custom Rendering
454
455
Advanced customization through render prop functions for complete visual control.
456
457
```javascript { .api }
458
/**
459
* Custom render function for thumb elements
460
* @param props - Props to spread into thumb element
461
* @param state - Current thumb and slider state
462
* @returns React element for the thumb
463
*/
464
renderThumb?: (props: ThumbProps, state: ThumbState) => React.ReactElement;
465
466
/**
467
* Custom render function for track elements
468
* @param props - Props to spread into track element
469
* @param state - Current track and slider state
470
* @returns React element for the track
471
*/
472
renderTrack?: (props: TrackProps, state: TrackState) => React.ReactElement;
473
474
/**
475
* Custom render function for mark elements
476
* @param props - Props to spread into mark element
477
* @returns React element for the mark
478
*/
479
renderMark?: (props: MarkProps) => React.ReactElement;
480
```
481
482
**Usage Examples:**
483
484
```javascript
485
// Custom thumb with value display
486
<ReactSlider
487
renderThumb={(props, state) => (
488
<div {...props} className="custom-thumb">
489
<span className="thumb-value">{state.valueNow}</span>
490
</div>
491
)}
492
defaultValue={[20, 80]}
493
/>
494
495
// Custom track with gradient
496
<ReactSlider
497
renderTrack={(props, state) => (
498
<div
499
{...props}
500
className={`custom-track track-${state.index}`}
501
style={{
502
...props.style,
503
background: state.index === 1
504
? 'linear-gradient(to right, #ff6b6b, #4ecdc4)'
505
: '#e9ecef'
506
}}
507
/>
508
)}
509
defaultValue={[30, 70]}
510
/>
511
512
// Custom marks with labels
513
<ReactSlider
514
marks={[0, 25, 50, 75, 100]}
515
renderMark={(props) => (
516
<span {...props} className="custom-mark">
517
{props.key}%
518
</span>
519
)}
520
defaultValue={50}
521
/>
522
```
523
524
### Keyboard Navigation
525
526
Built-in keyboard support for accessibility and ease of use.
527
528
**Supported Keys:**
529
- **Arrow Left/Down**: Decrease value by one step
530
- **Arrow Right/Up**: Increase value by one step
531
- **Home**: Jump to minimum value
532
- **End**: Jump to maximum value
533
- **Page Down**: Decrease by page step (customizable via `pageFn`)
534
- **Page Up**: Increase by page step (customizable via `pageFn`)
535
536
**Usage Examples:**
537
538
```javascript
539
// Custom page step function
540
<ReactSlider
541
pageFn={(step) => step * 5} // Page Up/Down moves by 5x step
542
step={2}
543
defaultValue={50}
544
/>
545
```
546
547
## Instance Methods
548
549
### getValue
550
551
```javascript { .api }
552
/**
553
* Returns the current slider value(s) in output format
554
* @returns Current value (number for single thumb, array for multiple thumbs)
555
*/
556
getValue(): number | number[];
557
```
558
559
**Usage Examples:**
560
561
```javascript
562
function SliderWithRef() {
563
const sliderRef = useRef(null);
564
565
const getCurrentValue = () => {
566
if (sliderRef.current) {
567
console.log('Current value:', sliderRef.current.getValue());
568
}
569
};
570
571
return (
572
<div>
573
<ReactSlider ref={sliderRef} defaultValue={[20, 80]} />
574
<button onClick={getCurrentValue}>Get Current Value</button>
575
</div>
576
);
577
}
578
```
579
580
## Type Definitions
581
582
### Default Props
583
584
```javascript { .api }
585
// Default prop values applied when not specified
586
const defaultProps = {
587
min: 0,
588
max: 100,
589
step: 1,
590
pageFn: (step) => step * 10,
591
minDistance: 0,
592
defaultValue: 0,
593
orientation: 'horizontal',
594
className: 'slider',
595
thumbClassName: 'thumb',
596
thumbActiveClassName: 'active',
597
trackClassName: 'track',
598
markClassName: 'mark',
599
withTracks: true,
600
pearling: false,
601
disabled: false,
602
snapDragDisabled: false,
603
invert: false,
604
marks: [],
605
renderThumb: (props) => React.createElement('div', props),
606
renderTrack: (props) => React.createElement('div', props),
607
renderMark: (props) => React.createElement('span', props)
608
};
609
```
610
611
### Value Formats
612
613
```javascript { .api }
614
// Single value mode
615
type SingleValue = number;
616
617
// Multi-value mode
618
type MultiValue = number[];
619
620
// Combined value type
621
type SliderValue = SingleValue | MultiValue;
622
623
// Event handler signatures
624
type ChangeHandler = (value: SliderValue, thumbIndex: number) => void;
625
type ClickHandler = (value: number) => void;
626
```