-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathuseRadioGroup.ts
More file actions
32 lines (27 loc) · 1.04 KB
/
useRadioGroup.ts
File metadata and controls
32 lines (27 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { ForwardedRef, useCallback, useEffect, useRef } from 'react';
const useRadioGroup = (defaultValue?: string, externalRef?: ForwardedRef<HTMLInputElement>) => {
const ref = useRef<HTMLDivElement | null>(null);
const setDefaultValueCheck = useCallback(
(el: HTMLInputElement, targetValue?: string, extRef?: ForwardedRef<HTMLInputElement>) => {
const isUnavailable = el.hasAttribute('readonly') || el.hasAttribute('disabled');
if (targetValue && targetValue === el.value && !isUnavailable) {
Object.assign(el, { checked: true });
}
if (extRef && typeof extRef === 'function') {
extRef(el);
}
return el;
},
[]
);
useEffect(() => {
if (ref.current) {
const radioElements = ref.current.querySelectorAll('input[type="radio"]') as NodeListOf<HTMLInputElement>;
radioElements.forEach(el => {
setDefaultValueCheck(el, defaultValue, externalRef);
});
}
}, [defaultValue, externalRef, setDefaultValueCheck]);
return ref;
};
export default useRadioGroup;