Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  6] [ 3]  / answers: 1 / hits: 17914  / 6 Years ago, mon, june 25, 2018, 12:00:00

I have a form.



I try to submit this form from a different function.



To do so I created a ref. This ref, when printed, has the correct HTML Node and this node also has an submit method. When this submit method is called (formNode.submit()) the form get's submitted, but the onSubmit handler is never triggered.



Why?



Here is a simplified example which shows the same behavior.



class Form extends React.Component {
constructor() {
super();

this.form = React.createRef();
}

render() {
return (
<div onClick={() => this.form.submit()}>
Click me!
<form
onSubmit={e => console.log(e)}
ref={f => (this.form = f)}
/>
</div>
);
}
}


https://codesandbox.io/s/vm8pkmony


More From » reactjs

 Answers
23

For your specific use case, you'll have to fire the submit event of the form using dispatchEvent.



this.form.dispatchEvent(new Event(submit));

[#54119] Thursday, June 21, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaceyr

Total Points: 510
Total Questions: 97
Total Answers: 116

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
kaceyr questions
;