Lesson 9 - Forms In React

9.2 - Handling Form Submission And Basic Validation

Right now, we have a form that takes the user name and email as input. Let's create a handler and validation function, defining what to do with these data.

Have a look at the following example,

import React, { useState } from 'react';

function App() {
 const [name, setName] = useState('');
 const [email, setEmail] = useState('');
 const [errors, setErrors] = useState({});

 const validate = () => {
    const errors = {};
    if (!name) errors.name = 'Name is required';
    if (!email) errors.email = 'Email is required';
    setErrors(errors);
    return Object.keys(errors).length === 0;
 };

 const handleSubmit = (event) => {
    event.preventDefault();
        if (validate()) {
            alert(`Submitted name: ${name}, email: ${email}`);
        }
        else {
            alert('Missing inputs: ')
        }
 };

 return (
 <form onSubmit={handleSubmit}>
    <label>
        Name:
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
    </label>
    <br />
    <label>
        Email:
        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
    </label>
    <br />
    <button type="submit">Submit</button>
 </form>
 );
}

Notice that we declared another state for capturing errors. We have two functions here:

  • validate - This function checks if the user filled both the input fields (name and email). If any of the fields are missing, it updates the errors state with the setErrors and returns the length of the error.
  • handleSubmit - This function is called when the user clicks the submit button. If the validate function returns errors, then it shows an error message Missing inputs., otherwise it processes the data.