useRadioButton
라디오 버튼 하나와 라디오 버튼 그룹의 상태, 체크 로직, ARIA 속성을 관리하는 훅들이에요. 라디오 버튼은 그냥 체크된 상태 하나를 다루는 것 같지만, 그룹 안에서 선택값을 공유해야 하고 시각적 박스까지 맞물리다 보면 직접 만들기 번거롭죠. 그 부분을 정리해 줘요.
출처: 문서
본문
사용법 (Usage)
import { useRadioButton } from '@primereact/headless/radiobutton';
import { useRadioButtonGroup } from '@primereact/headless/radiobuttongroup';
const group = useRadioButtonGroup({ defaultValue: 'a' });
const { rootProps, inputProps, boxProps, indicatorProps, state } = useRadioButton({
value: 'a',
checked: group.state.value === 'a',
onCheckedChange: (e) => group.updateChange({ ...e, value: 'a' })
});
<div {...rootProps}>
<input {...inputProps} className="sr-only" />
<div {...boxProps}>{state.checked && <span {...indicatorProps} />}</div>
</div>;
useRadioButton은 단일 옵션의 체크 상태를, useRadioButtonGroup은 그룹 전체에서 공유되는 값을 관리해요. 컴포넌트 기반 API가 필요하다면 Primitive 문서를 확인해 주세요.
기능 (Features)
- 조합 가능한 부분:
root,input,box,indicator요소에 prop을 펼쳐 시각적 제어를 완전히 가져갈 수 있어요 - 그룹 조정:
useRadioButtonGroup이 선택된 값을 보관하고 자식 라디오를 위한updateChange를 노출해요 - 제어 또는 비제어:
checked/onCheckedChange로 조종하거나defaultChecked로 상태를 훅에 맡겨요 - 접근 가능한 프리미티브: 숨겨진 네이티브 input이 포커스 관리와 키보드 의미를 온전히 유지해요
- 상태 플래그:
disabled와readOnly가 적절한 ARIA와data-*속성을 내보내요
콜백 다루기 (Working with callbacks)
제어형 라디오
검증이 컴포넌트 바깥에 있을 때처럼 외부에서 상태를 소유하려면 checked와 onCheckedChange를 전달해요.
const [checked, setChecked] = React.useState(true);
useRadioButton({
checked,
onCheckedChange: (e) => setChecked(e.checked)
});
콜백은 { originalEvent, checked }를 받는데, 여기서 checked가 새로운 불리언이에요.
공유 값을 가진 그룹
useRadioButtonGroup이 선택된 값을 소유하고, 각 라디오는 checked를 유도하고 updateChange로 이벤트를 전달해요.
const group = useRadioButtonGroup({ defaultValue: 'a' });
const radioA = useRadioButton({
value: 'a',
checked: group.state.value === 'a',
onCheckedChange: (e) => group.updateChange({ ...e, value: 'a' })
});
제어형 그룹
변경에 반응하거나, 값을 영속화하거나, 부모 상태에서 재설정해야 한다면 그룹 값을 끌어올려요.
const [value, setValue] = React.useState<unknown>('a');
const group = useRadioButtonGroup({
value,
onValueChange: (e) => setValue(e.value)
});
읽기 전용 선택
readOnly를 쓰면 라디오가 포커스 가능한 상태(스크린 리더는 계속 알려줘요)를 유지하면서 상태 변경만 막을 수 있어요. 검토 화면에 유용해요.
useRadioButton({ readOnly: true });
데이터 속성으로 스타일링 (Styling with data attributes)
모든 prop 객체에는 data-scope="radiobutton"과 data-part 속성이 포함되고, 상태 의존 속성이 자동으로 추가돼요.
| Scope | Part | States |
|---|---|---|
radiobutton |
root |
data-checked, data-disabled |
radiobutton |
box |
data-checked |
radiobutton |
indicator |
data-checked |
[data-scope='radiobutton'][data-part='box'] {
width: 1.125rem;
height: 1.125rem;
border: 1px solid #ccc;
border-radius: 9999px;
}
[data-scope='radiobutton'][data-part='box'][data-checked] {
background: var(--p-primary-color);
border-color: var(--p-primary-color);
}
[data-scope='radiobutton'][data-part='indicator'][data-checked] {
width: 0.625rem;
height: 0.625rem;
border-radius: 9999px;
background: white;
}
[data-scope='radiobutton'][data-part='root'][data-disabled] {
opacity: 0.5;
cursor: not-allowed;
}
API
useRadioButton
useRadioButtonGroup
접근성 (Accessibility)
방향키로 같은 그룹 안의 라디오 사이를 이동하고, 포커스된 라디오는 자동으로 선택돼요. 전체 WAI-ARIA 준수 세부 사항은 Primitive 문서를 참고하세요.