primitives
primitives copied to clipboard
[bug]: Checkbox in a form with onClick on parent causes infinite state update
Bug report
Current Behavior
With the simple example of
function App() {
const [isChecked, setIsChecked] = useState(false);
return (
<form>
<div onClick={() => setIsChecked((prev) => !prev)}>
<Checkbox checked={isChecked} />
<span>test</span>
</div>
</form>
)
}
The app crashed due to infinite state updates. Stopping propogation does nothing.
Expected behavior
The checkbox goes from unchecked to checked
Reproducible example
Suggested solution
Stop firing onClick multiple times. Perhaps make the checkbox into an actual <input type='checkbox'>
Your environment
| Software | Name(s) | Version |
|---|---|---|
| Radix Package(s) | checkbox | 1.1.2 |
| React | n/a | 18.3 |
| Browser | chrome | 130 |
| Assistive tech | ||
| Node | n/a | |
| npm/yarn | ||
| Operating System | windows | 11 |
Relates to #https://github.com/radix-ui/primitives/issues/2549#issuecomment-2070021911
Same here, really annoying
Same here!
I found a workaround by wrapping the Checkbox.Root component with memo.
See in CodeSandbox
Found the same (?) bug in slightly different scenario : https://github.com/radix-ui/primitives/issues/3265
Found a workaround with
onClick={(e) => {
const target = e.target as HTMLElement;
if (target.closest('input')) {
return;
}
setIsChecked((prev) => !prev)
}}
@andersonba This is the only solution that worked with me.