React
Lesson 1 - Introduction
Lesson 3 - Components In React
Lesson 4 - Props
Lesson 5 - Hooks
Lesson 6 - States
Lesson 7 - Conditional Rendering
Lesson 8 - Styling In React
Lesson 10 - `UseEffect` Hook
Lesson 11 - Web Service Calls In React
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.