react: Bug: `preventDefault()` breaks checkboxes, they may not reflect the `checked` prop

React version: 18.2.0

Steps To Reproduce

  1. call event.preventDefault() in onChange or onClick handler
  2. the checkbox element may not reflect the checked={checked} prop in some cases

Link to code example: https://codesandbox.io/s/relaxed-taussig-ypxiuo?file=/src/App.js

Recording 2022-08-09 at 18 23 20

The current behavior

I can’t click on <input type="checkbox" /> reliably anymore. ~It’s preventing us from adopting React 18 in a project, as some of our tests are broken by this bug.~ We’ve refactored our components so we’re not affected anymore, but it’s still a valid bug.

The expected behavior

React 18 should always respect the checked={checked} prop.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 16

Most upvoted comments

I think you are restricting the default behavior of checkbox by adding preventDefault() resulting the different behavior.

Hi there,

Try event.stopPropagation()

I encountered this issue while playing around with react 18 sandbox here I just removed the e.preventDefault() inside the function. I post this comment here in case someone needs it.

https://codesandbox.io/s/relaxed-taussig-ypxiuo?file=/src/App.js I think “broken in a different pattern” works correctly because a state change happens and after it happens preventDefault, You can verify this by clicking on the div and then on the input.

okay. I am not sure whether this satisfies you requirement or not but you can try return false instead of preventDefault() which is also used for preventing default browser behavior.

check the source here

Hi,

You can use both.