# Slider URL: /react/components/slider Source: https://github.com/daangn/seed-design/blob/dev/docs/content/react/components/slider.mdx A component that allows selecting and inputting one or two values within a specified range. 사용 가능 버전: @seed-design/react@1.1.0, @seed-design/css@1.1.0 ## Preview ```tsx import { Slider } from "seed-design/ui/slider"; export default function SliderPreview() { return "Value"} />; } ``` ## Installation - npm: npx @seed-design/cli@latest add ui:slider - pnpm: pnpm dlx @seed-design/cli@latest add ui:slider - yarn: yarn dlx @seed-design/cli@latest add ui:slider - bun: bun x @seed-design/cli@latest add ui:slider ## Props ## Examples ### Basic Set the value range of the slider by setting `min` and `max`. ```tsx import { VStack } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; export default function SliderBasic() { return ( "값"} /> "값"} /> ); } ``` ### Steps You can configure so values can only be selected at specific intervals. ```tsx import { Slider } from "seed-design/ui/slider"; import { useState } from "react"; import { VStack, Text } from "@seed-design/react"; export default function SliderSteps() { const [value, setValue] = useState([50]); return ( "값"} /> {JSON.stringify(value)} ); } ``` ### Allowed Values You can limit the values that can be selected on the slider using the `allowedValues` prop. When `allowedValues` is specified, `step` and `minStepsBetweenThumbs` are ignored. ```tsx import { VStack, Text } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; import { useState } from "react"; const ALLOWED_VALUES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; export default function SliderAllowedValues() { const [values, setValues] = useState([ALLOWED_VALUES[0], ALLOWED_VALUES[2]]); return ( ({ label: value, value }))} getAriaLabel={() => "값"} /> {JSON.stringify(values)} ); } ``` ### With Ticks You can display tick marks on the slider track. #### Thin Mainly used when the step is small enough to feel continuous. ```tsx import { Slider } from "seed-design/ui/slider"; export default function SliderTicksThin() { return ( "값"} /> ); } ``` #### Thick Mainly used when the step is large enough to feel discrete or when the thumb can only be positioned on ticks. ```tsx import { Slider } from "seed-design/ui/slider"; export default function SliderTicksThick() { return ( "값"} /> ); } ``` ### With Markers You can display markers below the slider. Screen readers do not read markers. If you need to inform the user when a specific value is selected, use the [`getAriaValuetext` prop](#getariavaluetext) to also provide text describing the currently selected value. ```tsx import { VStack } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; export default function SliderMarkers() { return ( `${value}°C`} getValueIndicatorLabel={({ value }) => `${value}°C`} getAriaLabel={() => "온도"} /> "값"} /> ); } ``` ### Controlled Control the slider's state externally using the `values` and `onValuesChange` props. ```tsx import { VStack, HStack, Text } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; import { ActionButton } from "seed-design/ui/action-button"; import { useState } from "react"; const DEFAULT_VALUE = [50]; export default function SliderControlled() { const [value, setValue] = useState(DEFAULT_VALUE); return ( "값"} /> {JSON.stringify(value)} setValue([0])} variant="neutralWeak"> Set Min setValue(DEFAULT_VALUE)} variant="neutralWeak"> Reset setValue([100])} variant="neutralWeak"> Set Max ); } ``` ### Listening to Value Changes - `onValuesChange` - Called whenever the slider's value changes. Use this prop to track the slider's value in real time. - `onValuesCommit` - Called when the slider's value change is complete. Useful for finalizing the value when the user finishes manipulating the slider and releases. ```tsx import { VStack, Text, HStack } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; import { useState } from "react"; export default function SliderOnValuesCommit() { const [value, setValue] = useState([20]); const [committedValue, setCommittedValue] = useState([20]); return ( "값"} /> Current value: {JSON.stringify(value)} Committed value: {JSON.stringify(committedValue)} ); } ``` ### Disabled ```tsx import { VStack } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; export default function SliderDisabled() { return ( "값"} /> (thumbIndex === 0 ? "최소값" : "최대값")} /> ); } ``` ### Hide Range Use the `hideRange` prop to hide the default range color and apply custom styles. ```tsx import { VStack } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; export default function SliderHideRange() { return ( "값"} /> (thumbIndex === 0 ? "최소값" : "최대값")} /> ); } ``` ### Customizing Value Indicator #### Value Indicator Label Use the `getValueIndicatorLabel` prop to customize the content of the tooltip displayed above the thumb. The Value Indicator is displayed only while the thumb is pressed, and screen readers do not read the content of the Value Indicator. If the Value Indicator contains meaningful content, it is recommended to also use the [`getAriaValuetext` prop](#getariavaluetext). ```tsx import { Slider } from "seed-design/ui/slider"; const formatter = new Intl.NumberFormat("ko-KR", { style: "decimal" }); export default function SliderCustomValueIndicatorLabel() { return ( ( <> thumb {thumbIndex}
{formatter.format(value)} )} getAriaValuetext={formatter.format} getAriaLabel={() => "값"} /> ); } ``` #### Value Indicator Trigger You can set the condition under which the value indicator is displayed with the `valueIndicatorTrigger` prop. The default value is `"auto"`, where the Value Indicator display condition varies based on the device environment. - **Mouse environment**: The Value Indicator is displayed on thumb hover. Setting `valueIndicatorTrigger="hover"` always behaves this way. - **Touch environment**: The Value Indicator is displayed on thumb active. Setting `valueIndicatorTrigger="active"` always behaves this way. When focusing the thumb via keyboard, the Value Indicator is always displayed regardless of the `valueIndicatorTrigger` value. ```tsx import { VStack } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; export default function SliderValueIndicatorTrigger() { return ( "값"} /> "값"} /> "값"} /> ); } ``` #### Hide Value Indicator Use the `hideValueIndicator` prop to hide the Value Indicator tooltip displayed above the thumb. ```tsx import { Slider } from "seed-design/ui/slider"; export default function SliderHideValueIndicator() { return ( "값"} /> ); } ``` ### Range Slider You can select a range using two thumbs. ```tsx import { VStack } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; import { useState } from "react"; export default function SliderRange() { const [priceRange, setPriceRange] = useState([20, 80]); return ( (thumbIndex === 0 ? "최소값" : "최대값")} /> ); } ``` #### Minimum Steps Between Thumbs You can set the minimum spacing between two thumbs. ```tsx import { VStack, Text } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; import { useState } from "react"; export default function SliderRangeMinSteps() { const [values, setValues] = useState([20, 80]); return ( (thumbIndex === 0 ? "최소값" : "최대값")} /> {JSON.stringify(values)} ); } ``` ### Accessibility #### `getAriaValuetext` By default, screen readers read the numeric value that each thumb points to. If the numeric value alone cannot sufficiently convey information, use the `getAriaValuetext` prop to provide a human-friendly description. You can add units or include text describing the meaning of the value. ```tsx import { VStack, Text } from "@seed-design/react"; import { useState } from "react"; import { Slider } from "seed-design/ui/slider"; const days = ["일", "월", "화", "수", "목", "금", "토"]; function getHumanReadableDayOfWeek(value: number) { if (days[value] === undefined) throw new Error("Invalid day value"); return `${days[value]}요일`; } export default function SliderGetAriaValuetext() { const [values, setValues] = useState([1, 3]); return ( ({ label, value }))} ticks={days.slice(1, -1).map((_, index) => index + 1)} tickWeight="thick" values={values} onValuesChange={setValues} getAriaLabel={(thumbIndex) => (thumbIndex === 0 ? "시작" : "종료")} getAriaValuetext={getHumanReadableDayOfWeek} getValueIndicatorLabel={({ value }) => getHumanReadableDayOfWeek(value)} /> values: {JSON.stringify(values)} aria-valuetext: {JSON.stringify(values.map(getHumanReadableDayOfWeek))} ); } ``` #### `getAriaLabel` and `getAriaLabelledby` Use the `getAriaLabel` or `getAriaLabelledby` prop to provide a description for each thumb. This helps screen reader users understand the purpose of each thumb. **Especially for range-selection sliders, you should describe the role each thumb plays in the range. (minimum-maximum, start-end, etc.)** ```tsx import { VStack, Text, type SliderRootProps } from "@seed-design/react"; import { useState } from "react"; import { Slider } from "seed-design/ui/slider"; const getAriaLabel: NonNullable = (thumbIndex) => thumbIndex === 0 ? "최소값" : "최대값"; export default function SliderGetAriaLabel() { const [values, setValues] = useState([10, 30]); return ( values: {JSON.stringify(values)} aria-label: {JSON.stringify(values.map((_, index) => getAriaLabel(index)))} ); } ``` ### Field Integration You can use Field-related props such as `label`, `description`, and `errorMessage`. ```tsx import { Divider, VStack } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; const markers = [ { value: 0, label: "매우 동의하지 않음" }, { value: 14, label: "매우 동의함" }, ]; export default function SliderField() { return ( `${value} ${markers.find((marker) => marker.value === value)?.label ?? ""}`.trim() } /> ); } ``` ### Use Cases #### Form (Uncontrolled) ```tsx import { HStack, VStack } from "@seed-design/react"; import { useCallback, useState, type FormEvent } from "react"; import { ActionButton } from "seed-design/ui/action-button"; import { Slider } from "seed-design/ui/slider"; type FieldErrors = { rating?: string; priceRange?: string; }; export default function SliderForm() { const [fieldErrors, setFieldErrors] = useState({}); const handleSubmit = useCallback((event: FormEvent) => { event.preventDefault(); const formData = new FormData(event.currentTarget); const rating = Number(formData.get("rating")); const priceRangeValues = formData.getAll("price-range").map(Number); const newFieldErrors: FieldErrors = {}; if (rating < 3) { newFieldErrors.rating = "평점은 최소 3점 이상이어야 합니다"; } const [min, max] = priceRangeValues; if (max - min < 20) { newFieldErrors["priceRange"] = "가격 범위는 최소 20만원 이상 차이가 나야 합니다"; } setFieldErrors(newFieldErrors); if (Object.keys(newFieldErrors).length > 0) return; window.alert(JSON.stringify({ rating, "price-range": priceRangeValues }, null, 2)); }, []); return (
`${value}점`} getAriaValuetext={(value) => `${value}점`} showRequiredIndicator {...(fieldErrors.rating && { invalid: true, errorMessage: fieldErrors.rating, })} /> `${value}만원`} getAriaValuetext={(value) => `${value}만원`} getAriaLabel={(index) => (index === 0 ? "최소 가격" : "최대 가격")} showRequiredIndicator {...(fieldErrors["priceRange"] && { invalid: true, errorMessage: fieldErrors["priceRange"], })} /> 제출
); } ``` #### React Hook Form ```tsx import { HStack, VStack } from "@seed-design/react"; import { useCallback, type FormEvent } from "react"; import { useController, useForm } from "react-hook-form"; import { ActionButton } from "seed-design/ui/action-button"; import { Slider } from "seed-design/ui/slider"; interface FormValues { rating: number; priceRange: [number, number]; } export default function SliderReactHookForm() { const { handleSubmit, reset, control } = useForm({ reValidateMode: "onSubmit", defaultValues: { rating: 2.5, priceRange: [20, 80], }, }); const { field: { value: ratingValue, onChange: ratingOnChange, onBlur: __ratingOnBlur, ...ratingField }, fieldState: ratingFieldState, } = useController({ name: "rating", control, rules: { validate: (value) => value >= 3 || "평점은 최소 3점 이상이어야 합니다", }, }); const { field: { value: priceRangeValue, onChange: priceRangeOnChange, onBlur: __priceRangeOnBlur, ...priceRangeField }, fieldState: priceRangeFieldState, } = useController({ name: "priceRange", control, rules: { validate: (value) => { const [min, max] = value; return max - min >= 20 || "가격 범위는 최소 20만원 이상 차이가 나야 합니다"; }, }, }); const onValid = useCallback( (data: FormValues) => window.alert(JSON.stringify(data, null, 2)), [], ); const onReset = useCallback( (event: FormEvent) => { event.preventDefault(); reset(); }, [reset], ); return ( ratingOnChange(values)} markers={[ { value: 0, label: "0점" }, { value: 5, label: "5점" }, ]} getValueIndicatorLabel={({ value }) => `${value}점`} getAriaValuetext={(value) => `${value}점`} showRequiredIndicator {...ratingField} /> `${value}만원`} getAriaValuetext={(value) => `${value}만원`} getAriaLabel={(index) => (index === 0 ? "최소 가격" : "최대 가격")} minStepsBetweenThumbs={2} showRequiredIndicator {...priceRangeField} /> 초기화 제출 ); } ``` ### RTL Support ```tsx import { VStack } from "@seed-design/react"; import { Slider } from "seed-design/ui/slider"; export default function SliderRtl() { return ( `${value}°C`} getValueIndicatorLabel={({ value }) => `${value}°C`} getAriaLabel={() => "온도"} /> "값"} /> ); } ```