How to Prevent form submission in React

avatar

Borislav Hadzhiev

Last updated: May 2, 2022

banner

Photo from Unsplash

Prevent form submission in React #

Use the preventDefault() method on the event object to prevent form submission in React, e.g. event.preventDefault(). The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.

App.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleSubmit = event => { // 👇️ prevent page refresh event.preventDefault(); console.log('form submitted ✅'); }; return ( <div> <form onSubmit={handleSubmit}> <input type="text" id="message" name="message" value={message} onChange={event => setMessage(event.target.value)} /> <button type="submit">Submit</button> </form> </div> ); }; export default App;

We have a button element with a type prop set to submit in a form.

The form element has an onSubmit handler, so every time the button is clicked or the Enter key is pressed, the handleSubmit function is invoked.

By default, the browser will refresh the page when a form submission event is triggered.

We generally want to avoid this in React.js applications because it would cause us to lose our state.

To prevent the default browser behavior, we have to use the preventDefault() method on the event object.

App.js
const handleSubmit = event => { // 👇️ prevent page refresh event.preventDefault(); console.log('form submitted ✅'); };

Note that the native browser validation features still function as expected, even though we've used the preventDefault() method.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.