Submit form in ReactJS using BUTTON element

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>

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;

Tags:

Reactjs