Try like this:
First, add a props inside every RadioFieldItem
to pass the selected
value:
<RadioField
// LOOK HERE
// key={selected}
selectedValue={selected}
>
<RadioFieldItem
selected={selected}
value="yes"
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setSelected(e.target.value)
}
/>
<RadioFieldItem
selected={selected}
value="no"
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setSelected(e.target.value)
}
/>
<RadioFieldItem
selected={selected}
value="maybe"
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setSelected(e.target.value)
}
/>
</RadioField>
Then, inside the RadioFieldItem
component use a conditional to check if the selected value is equal than the item name:
export function RadioFieldItem({ value, isDisabled = false, onChange, selected }) {
const [id, setId] = React.useState(generateId());
const { activeIndex, setActiveIndex } = React.useContext(RadioFieldContext);
const isRadioSelected = (value: string | undefined): boolean =>
activeIndex === value;
const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
setActiveIndex &&
setActiveIndex((prevState) => {
onChange && onChange(e);
return e.target.value;
});
};
return (
<div>
<input
type="radio"
name={id}
id={id}
value={value}
checked={selected==value}
onChange={isDisabled ? undefined : handleChange}
/>
<label htmlFor={id}>{capitalizeFirstLetter(value)}</label>
</div>
);
}