Reputation: 270
I'm building the form using ReactJS and if it has <input type="submit">
element it works fine: forms submits by pressing enter in input[type="text"]
and by pressing submit element (And there are also working checkings by ReactJS when form is not submitted if nothing has changed).
But if I replace input[type="submit"]
with <button>ButtonLabel</button>
I try to use 2 ways:
Get form DOMNode element and call .submit() method which is not ok because it doesn't use internal ReactJS logic
Pass params to button like
<button type="submit" form="form-id">
but it still doesn't use ReactJS checkings (I don't want to submit the form if nothing has changed)
So I would really appreciate if someone will suggest me how to submit the form in ReactJS correctly using BUTTON element.
Upvotes: 19
Views: 98206
Reputation: 4843
In React Hooks (16.8.0 and above), use the onSubmit
handler and e.preventDefault()
:
import React, { useState } from 'react';
const Form = () => {
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(`Form submitted, ${name}`);
}
return(
<form onSubmit = {handleSubmit}>
<input onChange = {(e) => setName(e.target.value)} value = {name}></input>
<button type = 'submit'>Click to submit</button>
</form>
);
}
export default Form;
Upvotes: 7
Reputation: 2787
The button element should work exactly as you expect providing the type is set to a submit button and the form has an onsubmit
handler.
<form ref="form" onSubmit={this.handleSubmit}>
<button type="submit">Do the thing</button>
</form>
Upvotes: 39