blob: 297800d9d56a7509644e430ce437ec4c9895acdb (
plain) (
blame)
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
33
34
35
36
37
|
import React, {ReactElement, useEffect, useId, useState} from "react";
/**
* A component for a group of radio buttons where only one can be selected
*
* @param props.children html <option> elements for each radio option
* @param props.value The option which is selected
* @param props.onChange A function that will be called when the selected option changes
*/
function RadioButtonGroup(props: { children: ReactElement<HTMLOptionElement>[], value: any, onChange?: (arg0: any) => void }) {
const [selected, setSelected] = useState(props.value);
useEffect(() => {
setSelected(props.value);
}, [props.value]);
useEffect(() => {
props.onChange && props.onChange(selected);
}, [selected])
return (
<div className="radio-group">
{ props.children.map((item) => (
<label>
<input
type="radio"
name={useId()}
value={item.props.value}
checked={item.props.value === selected}
onChange={e => setSelected(e.target.value)}
/>
{item.props.children.toString()}
</label>
)) }
</div>
)
}
export default RadioButtonGroup
|