Prevent page refresh on form submit in React.js

avatar

Borislav Hadzhiev

Mon Apr 18 20222 min read

Prevent page refresh on form submit in React.js #

Use the preventDefault() method on the event object to prevent a page refresh on form submit 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 [first, setFirst] = useState(''); const handleSubmit = event => { // 👇️ prevent page refresh event.preventDefault(); console.log('form submitted ✅'); }; return ( <div> <form onSubmit={handleSubmit}> <input type="text" id="first" name="first" value={first} onChange={event => setFirst(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.

prevent page refresh on form submit

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

Here is an example of setting the required prop on an input field.

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

native browser validation works

If you need to clear the input values after the for has been submitted, set the state variables to empty strings or to their respective initial values.

App.js
import {useState} from 'react'; const App = () => { const [first, setFirst] = useState(''); const handleSubmit = event => { event.preventDefault(); console.log('form submitted ✅'); // 👇️ clear input field values setFirst(''); }; return ( <div> <form onSubmit={handleSubmit}> <input type="text" id="first" name="first" value={first} onChange={event => setFirst(event.target.value)} /> <button type="submit">Submit</button> </form> </div> ); }; export default App;
Use the search field on my Home Page to filter through my more than 1,000 articles.