UNPKG

@yamada-ui/radio

Version:

Yamada UI radio component

90 lines (88 loc) 2.4 kB
"use client" // src/use-radio-group.ts import { useControllableState } from "@yamada-ui/use-controllable-state"; import { isObject, mergeRefs, useCallbackRef } from "@yamada-ui/utils"; import { useCallback, useId, useRef } from "react"; var isEvent = (value) => value && isObject(value) && isObject(value.target); var useRadioGroup = ({ id, name, defaultValue, isNative, value: valueProp, onChange: onChangeProp, ...props }) => { const uuid = useId(); id != null ? id : id = uuid; name != null ? name : name = `radio-${id}`; const containerRef = useRef(null); const onChangeRef = useCallbackRef(onChangeProp); const [value, setValue] = useControllableState({ defaultValue, value: valueProp, onChange: onChangeRef }); const onFocus = useCallback(() => { const container = containerRef.current; if (!container) return; let query = `input:not(:disabled):checked`; let firstInput = container.querySelector(query); if (firstInput) { firstInput.focus(); } else { query = `input:not(:disabled)`; firstInput = container.querySelector(query); firstInput == null ? void 0 : firstInput.focus(); } }, []); const onChange = useCallback( (evOrValue) => { const nextValue = isEvent(evOrValue) ? evOrValue.target.value : evOrValue; setValue(nextValue); }, [setValue] ); const getContainerProps = useCallback( (props2 = {}, ref = null) => ({ role: "radiogroup", ...props2, ref: mergeRefs(ref, containerRef) }), [] ); const getRadioProps = useCallback( (props2 = {}, ref = null) => { const checked = props2.value === value; return { ...props2, ref, name, "aria-checked": checked, [isNative ? "checked" : "isChecked"]: ( // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition value != null ? checked : void 0 ), // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition ...!isNative ? { checked: value != null ? checked : void 0 } : {}, onChange }; }, [name, value, onChange, isNative] ); return { id, name, props, setValue, value, getContainerProps, getRadioProps, onChange, onFocus }; }; export { useRadioGroup }; //# sourceMappingURL=chunk-RSGQTWJA.mjs.map