final-form / react-final-form

🏁 High performance subscription-based form state management for React
https://final-form.org/react
MIT License
7.38k stars 480 forks source link

Programmatic submit does not work in React 17 #878

Open MartijnHols opened 3 years ago

MartijnHols commented 3 years ago

Are you submitting a bug report or a feature request?

Bug

What is the current behavior?

Submission using form.dispatchEvent(new Event('submit', { cancelable: true })) does not work after upgrading to React 17.

Hit the image button here to see it do nothing:

https://codesandbox.io/s/react-final-form-external-submit-button-forked-kcrsu?file=/index.js

What is the expected behavior?

It submits the form, as it did prior to React 17. You can view this behavior by changing the React version in the sandbox.

Sandbox Link

https://codesandbox.io/s/react-final-form-external-submit-button-forked-kcrsu?file=/index.js

What's your environment?

RFF 6.5.2 FF 4.20.1 React 17

Other information

Sandbox is an updated version from https://final-form.org/docs/react-final-form/faq#via-documentgetelementbyid. No other changes.

lmpatmore commented 3 years ago

It looks like the solution to this is to make sure the event bubbles, highlighted in this comment: https://github.com/facebook/react/issues/20151#issuecomment-721000418

document.getElementById('myForm').dispatchEvent(new Event('submit', { cancelable: true, bubbles:true }))

neuralp commented 3 years ago

It looks like the solution to this is to make sure the event bubbles, highlighted in this comment: facebook/react#20151 (comment)

document.getElementById('myForm').dispatchEvent(new Event('submit', { cancelable: true, bubbles:true }))

I can verify that this does work and solved my issue as well.

tkharuk commented 3 years ago

I find this solution with direct dispatchEvent to be truly unnecessary.

Just use form id attribute + button form attribute to bind button to a form.

<form id="checkout">...</form>

<button type="submit" form="checkout">Submit</button>

I've tried to add this to official examples, but something went off. https://github.com/final-form/react-final-form/pull/750

wilz04 commented 1 year ago

Use form.requestSubmit() instead of form.submit() :)