In this post we'll see how to create a login form with validations using React and Bootstrap 5. The login form has two fields- email and password and a submit button.
LoginForm React and Bootstrap Example
In this example Bootstrap 5 is used.
If you want to know how to download Bootstrap and use in your React application, check this post- Installing Bootstrap in React
Login.js
import { useState } from "react"; const Login = () => { const [formField, setState] = useState({ email: '', passwd: '', errors: [] }); const handleInputChange = (event) => { let errors = []; // clear errors if any if (formField.errors.length > 0) { setState((prevState) => ( {...prevState, errors} )); } const value = event.target.value; const name = event.target.name; setState((prevState) => ( {...prevState, [name]: value} )); } const submitHandler = (event) => { event.preventDefault(); let errors = []; //email regular expression pattern const emailRegEx = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/; let isEmailValid = emailRegEx.test(formField.email.toLowerCase()) if (!isEmailValid) { errors.push("email"); } if(formField.passwd === ""){ errors.push("passwd"); } setState((prevState) => ( {...prevState, errors} )); // If there is error dont submit, return to form if (errors.length > 0) { return false; } else{ // write code for successful submission... console.log('Form Submitted') } } const hasError = (name) => { //console.log("haserror " + name); return formField.errors.indexOf(name) !== -1; } return ( <div className="card col-5 mt-5 mx-auto"> <div className="card-header bg-info text-white"> <h2>User Login</h2> </div> <div className="card-body"> <form onSubmit={submitHandler}> <div className="mb-3"> <label className="form-label" htmlFor="userEmail">Email</label> <input type="text" className={hasError("email") ? "form-control is-invalid" :"form-control"} placeholder="Enter Email" name="email" id="userEmail" value={formField.email} onChange={handleInputChange} /> <div className={hasError("email") ? "invalid-feedback" : ""}> { hasError("email") ? <span>Please enter valid email</span> : "" } </div> </div> <div className="mb-3"> <label className="form-label" htmlFor="userPassword">Password</label> <input type="password" className={hasError("passwd") ? "form-control is-invalid" :"form-control"} placeholder="Enter Password" name="passwd" id="userPassword" value={formField.passwd} onChange={handleInputChange}/> <div className={hasError("passwd") ? "invalid-feedback" : ""}> { hasError("passwd") ? <span>Please enter password</span> : "" } </div> </div> <button type="submit" className="btn btn-primary">Submit</button> </form> </div> </div> ) } export default Login;
Some important points about the login form are as given below-
- Uses the Bootstrap card as a container for the form elements.
- Single state is used here with useState() hook. State is managed as an object with three properties email, passwd and an array of errors which keeps track of all the fields that fail validations. Initial state is empty string for email and passwd, empty array ([]) for errors.
- In input fields
onChange()
event handler is mapped to a single functionhandleInputChange()
for all the fields. Note that a single setState() changes state for all the form fields. For that to work, ensure that the name you give to input fields matches the name of the properties in state object. - When calling setState() to update state, spread operator is used to spread the previous state so that you can
overwrite the individual fields without losing the data for other fields.
setState((prevState) => ( {...prevState, [name]: value} ));
- Form
onSubmit()
event handler is mapped tosubmitHandler()
function. That's where field validation is done and field name is pushed to errors array if field fails validation. - While rendering, errors array is checked. If field exists in that array that means field failed validation.
- When the field fails validation Bootstrap class "is-invalid" is added which creates red border around the field. For error message "invalid-feedback" class is used. You don't need to write any css yourself.
Clicking submit without entering any values.
When only email is entered.
That's all for the topic React Bootstrap Login Form With Validations. If something is missing or you have something to share about the topic please write a comment.
You may also like
- React Conditional Rendering With Examples
- How to Loop in React
- React Example - Remove Object From an Array of Objects
- React Dynamic Form Using Formik's FieldArray Component
- Nested Route in React
- Functional Interface in Java
- Bubble Sort Java Program
- tempfile Module in Python - Create Temporary File and Directory
- Spring Boot MVC Form Validation Example
- Spring Dependency Injection With Examples