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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
import Fieldset, { type FieldsetProps } from '@components/atoms/forms/fieldset';
import { ChangeEvent, FC, useState } from 'react';
import LabelledBooleanField, {
type LabelledBooleanFieldProps,
} from './labelled-boolean-field';
import styles from './radio-group.module.scss';
export type RadioGroupOption = Pick<
LabelledBooleanFieldProps,
'id' | 'label' | 'name' | 'value'
>;
export type RadioGroupProps = Pick<
FieldsetProps,
'className' | 'legend' | 'legendClassName'
> &
Pick<LabelledBooleanFieldProps, 'labelPosition' | 'labelSize'> & {
/**
* The default option value.
*/
initialChoice: string;
/**
* The legend position. Default: inline.
*/
legendPosition?: FieldsetProps['legendPosition'];
/**
* The options.
*/
options: RadioGroupOption[];
};
/**
* RadioGroup component
*
* Render a group of labelled radio buttons.
*/
const RadioGroup: FC<RadioGroupProps> = ({
className,
initialChoice,
labelPosition,
labelSize,
legendPosition = 'inline',
options,
...props
}) => {
const [selectedChoice, setSelectedChoice] = useState<string>(initialChoice);
const wrapperModifier = `wrapper--${legendPosition}`;
/**
* Update the selected choice based on the change event target.
*
* @param {ChangeEvent<HTMLInputElement>} e - The change event.
*/
const updateChoice = (e: ChangeEvent<HTMLInputElement>) => {
setSelectedChoice(e.target.value);
};
/**
* Retrieve an array of radio buttons.
*
* @returns {JSX.Element[]} The radio buttons.
*/
const getOptions = (): JSX.Element[] => {
return options.map((option) => (
<LabelledBooleanField
key={option.id}
checked={selectedChoice === option.value}
className={styles.option}
labelPosition={labelPosition}
labelSize={labelSize}
onChange={updateChoice}
type="radio"
{...option}
/>
));
};
return (
<Fieldset
className={`${styles.wrapper} ${styles[wrapperModifier]} ${className}`}
legendPosition={legendPosition}
{...props}
>
{getOptions()}
</Fieldset>
);
};
export default RadioGroup;
|