RangeSlider Component
RangeSlider is a reusable React component designed for selecting a value within a specified range. It is integrated with react-hook-form for seamless form handling.
Features
- Allows selection of a value within a defined range.
- Dynamically displays the current value of the slider.
- Uses a visually appealing gradient to indicate the selected range.
- Fully compatible with
react-hook-form.
Props
| Prop | Type | Description |
|---|---|---|
control | Control<TFieldValue> | The react-hook-form control object. |
name | Path<TFieldValue> | Name of the input field for form handling. |
sliderValue | number | Current value of the slider. |
min | number | Minimum value of the range. |
max | number | Maximum value of the range. |
Component
import React, { useMemo } from "react";
import { Controller, Control, Path, FieldValues } from "react-hook-form";
interface RangeSliderProps<TFieldValue extends FieldValues> {
control: Control<TFieldValue>;
name: Path<TFieldValue>;
sliderValue: number;
min: number;
max: number;
}
const RangeSlider = <TFormValues extends Record<string, any>>({
control,
name,
sliderValue,
min,
max,
}: RangeSliderProps<TFormValues>) => {
const valuePercentage = useMemo(() => {
return ((sliderValue - min) * 100) / (max - min);
}, [sliderValue]);
return (
<div className="flex items-center space-x-4">
<Controller
name={name}
control={control}
render={({ field }) => (
<input
{...field}
type="range"
min={min}
max={max}
className="w-full h-2 rounded-lg appearance-none cursor-pointer bg-gray-200"
style={{
background: `linear-gradient(to right, #4ade80 ${valuePercentage}%, #e5e7eb ${valuePercentage}%)`,
}}
/>
)}
/>
<span className="text-lg font-medium text-gray-700 dark:text-gray-300">
{sliderValue}
</span>
</div>
);
};
export default RangeSlider;
Usage
This component is typically used in forms where a user needs to select a value within a certain range, such as setting a preference level or defining a boundary.
Styling
Styled using Tailwind CSS, the RangeSlider component's appearance can be easily customized by altering the Tailwind classes within the component.
Accessibility
The component is designed with basic accessibility features, including keyboard navigability and focus management.
Dependencies
- React
^17.0.0or higher - react-hook-form
^7.0.0or higher - Tailwind CSS for styling
Notes
- Customize the
minandmaxprops as per the required range in your application. - Ensure that the
sliderValueis managed appropriately within the parent component or form.
This documentation provides a detailed overview of the RangeSlider component, explaining its features, props, styling, and dependencies. Adapt the paths and versions according to your project's configuration.