What is @react-aria/slider?
@react-aria/slider is a React library that provides accessible slider components. It is part of the React Aria collection of hooks and components that help build accessible web applications. The package offers a range of features to create sliders that are keyboard navigable and screen reader friendly.
Single Slider
This code demonstrates how to create a single slider using @react-aria/slider. It includes the necessary hooks and components to ensure the slider is accessible.
import { useSlider, useSliderThumb } from '@react-aria/slider';
import { useSliderState } from '@react-stately/slider';
import { VisuallyHidden } from '@react-aria/visually-hidden';
import { useRef } from 'react';
function SingleSlider(props) {
let trackRef = useRef(null);
let state = useSliderState(props);
let { groupProps, trackProps, thumbProps } = useSlider(props, state, trackRef);
let { thumbProps: thumbProps0, inputProps: inputProps0 } = useSliderThumb({ index: 0 }, state);
return (
<div {...groupProps}>
<div {...trackProps} ref={trackRef} style={{ position: 'relative', height: '4px', background: 'gray' }}>
<div {...thumbProps0} style={{ position: 'absolute', top: '-6px', left: `${state.getThumbPercent(0) * 100}%`, width: '20px', height: '20px', background: 'blue' }}>
<VisuallyHidden>
<input {...inputProps0} />
</VisuallyHidden>
</div>
</div>
</div>
);
}
Range Slider
This code demonstrates how to create a range slider with two thumbs using @react-aria/slider. It ensures both thumbs are accessible and can be controlled via keyboard and screen readers.
import { useSlider, useSliderThumb } from '@react-aria/slider';
import { useSliderState } from '@react-stately/slider';
import { VisuallyHidden } from '@react-aria/visually-hidden';
import { useRef } from 'react';
function RangeSlider(props) {
let trackRef = useRef(null);
let state = useSliderState(props);
let { groupProps, trackProps, thumbProps } = useSlider(props, state, trackRef);
let { thumbProps: thumbProps0, inputProps: inputProps0 } = useSliderThumb({ index: 0 }, state);
let { thumbProps: thumbProps1, inputProps: inputProps1 } = useSliderThumb({ index: 1 }, state);
return (
<div {...groupProps}>
<div {...trackProps} ref={trackRef} style={{ position: 'relative', height: '4px', background: 'gray' }}>
<div {...thumbProps0} style={{ position: 'absolute', top: '-6px', left: `${state.getThumbPercent(0) * 100}%`, width: '20px', height: '20px', background: 'blue' }}>
<VisuallyHidden>
<input {...inputProps0} />
</VisuallyHidden>
</div>
<div {...thumbProps1} style={{ position: 'absolute', top: '-6px', left: `${state.getThumbPercent(1) * 100}%`, width: '20px', height: '20px', background: 'blue' }}>
<VisuallyHidden>
<input {...inputProps1} />
</VisuallyHidden>
</div>
</div>
</div>
);
}