I have developed a basic React custom controlled radio button:
export const Radio: FC<RadioProps> = ({
label,
checked,
onChange,
disabled,
}) => {
const id = useId();
return (
<div>
<label
htmlFor={id}
className={clsx(
disabled ? 'cursor-not-allowed' : 'cursor-pointer',
'inline-flex items-center mr-4'
)}
>
<input
onChange={onChange} // This will be used to check the radio button
type="radio"
disabled={disabled}
id={id}
className="hidden"
/>
<div
className={clsx(
checked ? 'after:scale-1' : 'after:scale-0',
'radio__radio w-5 h-5 border-2 border-gray-400 rounded-full mr-2 box-border p-0.5',
"after:content-[''] after:block after:h-full after:w-full after:bg-green-500 after:rounded-full after:transform after:transition-transform after:duration-[35ms]"
)}
/>
{label}
</label>
</div>
);
};
Currently, I am displaying a collection of these radio buttons:
<div>
{items.map(({ label, id }) => {
return (
<Radio
key={id}
label={label}
checked={id === selected}
onChange={() => onSelect(id)}
/>
);
})}
</div>
The issue at hand is that the onChange
event for each radio button (within the input
) triggers only once, preventing users from reselecting a radio button. Users can switch between them but are unable to re-select one, as the onChange
in each button fires only once. How can I modify my Radio component to trigger the onChange
when reselecting a radio button?