🎁 Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

React clear a form after submit

Let’s explore how to clear forms in React after they are submitted.

If you want to see the live demo in action check it out on Github Pages and you can view the full code here.

Iteration 1: Resetting a React form after submit

A basic example of how we can clear a form after submitting can be made using mix of the onSubmit() and onChange() events plus the manual calling of the useState() hook.

Full code below:

const App = ()=> {
    // default form values
    const [formValues, setFormValues] = useState({
        model: "",
        manufacturer: "",
    })

    const [data, setData] = useState([])

    const handleSubmit = (e) => {
        e.preventDefault()
        setData([...data, formValues])
        setFormValues({
            model: "",
            manufacturer: "",
        })
    }

    return (
        <div className="App">
        <form onSubmit={(e) => handleSubmit(e)}>
            <input
                placeholder="Car model ..."
                value={formValues.model}
        name="model"
                onChange={(e) => setFormValues({ ...formValues, model: e.target.value })}
            />
            <br />
            <input
                placeholder="Car manufacturer ..."
                value={formValues.manufacturer}
        name="manufacturer"
                onChange={(e) => setFormValues({ ...formValues, manufacturer: e.target.value })}
            />
            <br/>
            <button type="submit">Save</button>
        </form>
    </div>)
}

In order to keep the values from before the reset, notice that we are storing them also in the data state variable.

Iteration 2: Making a form reset React hook

Given that we may need to reuse this reset feature in other forms, we can extract this behavior in its own useResetableForm(). This is the code for the hook:

const useResetableForm = (initialState) => {
    const [formValues, setFormValues] = useState(initialState)
    const handleChange = (e) => {
        const { name, value } = e.target
        setFormValues({ ...formValues, [name]: value })
    }
    const resetForm = () => setFormValues(initialState)
    return { formValues, handleChange, resetForm }
}

The useResetableForm() hook receives an initialState object and uses it to clear the form after it's submitted. It returns the following:

  • formValues an object with the values inputted by the user in the form. We need to save them before calling the resetForm() method
  • 'handleChange' needs to be called when an input is updated
  • resetForm() the method that will reset the form to the initialState

And this is how it will look when we wire up this hook with the previous form:

const App = ()=> {
    // default form values
    const defaultValues = {
        model: "",
        manufacturer: "",
    }

    // Use the useResetableForm hook to manage form state
    const { formValues, handleChange, resetForm } = useResetableForm(defaultValues)
    const [data, setData] = useState([])

    const handleSubmit = (e) => {
        e.preventDefault()
        setData([...data, formValues])
        resetForm()
    }

    return (
        <div className="App">
        <form onSubmit={(e) => handleSubmit(e)}>
            <input
                placeholder="Car model ..."
                value={formValues.model}
                name="model"
                onChange={handleChange}
            />

            <br />
            <input
                placeholder="Car manufacturer ..."
                value={formValues.manufacturer}
                name="manufacturer"
                onChange={handleChange}
            />
            <br/>
            <button type="submit">Save</button>
        </form>
    </div>)
}

A bit nicer, especially with the onChange={handleChange} part.

Iteration 3: Clearing selects and radio buttons from inputs with the form reset React hook

The last step will be to test if our useResetableForm() works with other inputs than basic text fields. Let's update the form with some select options and radio buttons.

We want the hook to reset all input types:

It works as expected!

Below is the full code of the example:

const App = ()=> {
    // default form values
    const defaultValues = {
        model: "",
        manufacturer: "",
        engine: null
    }

    // Use the useResetableForm hook to manage form state
    const { formValues, handleChange, resetForm } = useResetableForm(defaultValues)
    const [data, setData] = useState([])

    const handleSubmit = (e) => {
        e.preventDefault()
        setData([...data, formValues])
        resetForm()
    }

    console.log(data)

    return (
        <div>
            <form onSubmit={(e) => handleSubmit(e)}>
                <input
                    placeholder="Car model ..."
                    name="model"
                    value={formValues.model}
                    onChange={handleChange}
                />
                <br />
                <select
                    name="manufacturer"
                    value={formValues.manufacturer}
                    onChange={handleChange}>
                        <option>Select manufacturer ...</option>
                        <option>Doge</option>
                        <option>BMW</option>
                        <option>Ford</option>
                </select>
                <br />
                <input name="engine" value="electric" id='electric'
                    type="radio"
                    checked={formValues.engine === "electric"}
                    onChange={handleChange}
                />
                <label htmlFor="electric">Electric</label>
                <input name="engine" value="petrol" id='petrol'
                    type="radio"
                    checked={formValues.engine === "petrol"}
                    onChange={handleChange}
                />
                <label htmlFor="petrol">Petrol</label>
                <br />
                <button type="submit">Save</button>
            </form>
        </div>
    )
}

You can checkout the check out live demo on Github pages.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *