19

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:

  1. Get form DOMNode element and call .submit() method which is not ok because it doesn't use internal ReactJS logic

  2. 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.

2 Answers 2

39

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>
Sign up to request clarification or add additional context in comments.

1 Comment

and to add to this, you can do handleSubmit: function(e){ if (!this.validate()) { e.preventDefault() } }
8

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.