This React login component serves as a solid foundation for building authentication interfaces in modern web applications. It demonstrates how to handle to create reusable UI elements, useState, useRef, controlled components, prop forwarding, forwardRef and
manage form inputs, perform validation and use component composition to create reusable UI elements. By understanding and implementing these concepts, you can create robust and user-friendly forms that are both maintainable and scalable. Whether you’re working on a small project or a large enterprise application, mastering these techniques will significantly improve your development workflow.
1. Component Structure Overview
Login.js
import { useRef, useState } from "react" import Header from "./Header" import { checkValidate } from "../utils/validate" import InputText from "./InputText" const Login = () => { const [isSignInForm, setIsSignInForm] = useState(true) const [errorMessage, setErrorMessage] = useState(true) const email = useRef(null) const password = useRef(null) const firstName = useRef(null) const handleButtonClick = () => { setErrorMessage(checkValidate(email.current.value,password.current.value)) } const toggleSignInForm = () => { setIsSignInForm(!isSignInForm) } return ( <div> <form onSubmit={(e) => e.preventDefault()} > <h1>{isSignInForm ? "Sign In" : "Sign Up"}</h1> {!isSignInForm && ( <InputText placeholder={"First name"} ref={firstName} /> )} <InputText placeholder={"Name"} ref={email} /> <InputText placeholder={"Password"} ref={password} /> <button onClick={handleButtonClick}> {isSignInForm ? "Sign In" : "Sign Up"} </button> <p>{errorMessage}</p> <p onClick={toggleSignInForm}> <span>New to netflix?</span> {isSignInForm ? "SignUp Now" : "SignIn Now"} </p> </form> </div> )} export default Login
2. State Management with useState
The Login component relies on useState to manage two pieces of state:
- isSignInForm: A boolean that determines whether the form is in “Sign In” or “Sign Up” mode.
- errorMessage: A string or null that holds any validation error messages.
const [isSignInForm, setIsSignInForm] = useState(true) const [errorMessage, setErrorMessage] = useState(null)
- Sign In/Sign Up Toggle: This state toggles between sign-in and sign-up forms based on user action.
- Error Handling: The errorMessage state captures and displays validation errors, improving the user experience by providing immediate feedback.
3. Refs for DOM Manipulation with useRef
useRef is used to create references to the input elements
const email = useRef(null) const password = useRef(null) const firstName = useRef(null)
- Purpose of Refs: Refs allow direct access to the DOM elements. In this case, they help retrieve the values entered by the user without using controlled components (i.e., without the need to sync the input value with the component’s state).
- Why use Refs here? By using refs, the component can quickly access input values, making it easy to validate or manipulate these values as needed.
4. Form Handling and Validation
The handleButtonClick function handles the form submission logic:
const handleButtonClick = () => { setErrorMessage(checkValidate(email.current.value, password.current.value)) }
- Validation: The checkValidate function (imported from ../utils/validate) checks the validity of the email and password inputs. If validation fails, an error message is set, which will be displayed to the user.
- Immediate Feedback: The validation logic ensures that users receive instant feedback if their input doesn’t meet the required criteria, enhancing the overall user experience.
5. Input Components with Prop Forwarding with forwardRef() Hook
The InputText component is a reusable input field built using forwardRef
import React, { forwardRef } from "react"; const InputText = forwardRef((props, ref) => { console.log("myProps", props) return <input type="text" ref={ref} placeholder={props.placeholder} {...props} /> }) export default InputText
- forwardRef: This React method allows a component to forward its ref to a child component. This is crucial when you need to access the DOM element of a component but still want to keep the component reusable and flexible.
- props and …props: The props object holds all properties passed to the InputText component. Using {…props} spreads these properties onto the input element, allowing it to inherit attributes like placeholder, onChange, etc.
6. Form Toggle Functionality
The toggleSignInForm function toggles between the sign-in and sign-up forms:
const toggleSignInForm = () => { setIsSignInForm(!isSignInForm) }
- Dynamic Form Rendering: Based on the value of isSignInForm, the form dynamically renders either a sign-in or a sign-up form. This approach reduces redundancy by reusing the same form structure for both purposes.
7. Validation Logic
The checkValidate function ensures that user inputs are valid:
export const checkValidate = (email, password) => { const isEmailValid = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/.test(email) const isPasswordValid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]8,}$/.test(password) if (!isEmailValid) return "Email ID is not valid" if (!isPasswordValid) return "Password is not valid"; return null }
For Code
35 Comments
Pingback: Homepage
Pingback: āđāļŦāļĨāđāļēāļāļāļ
Pingback: āļāđāļēāļāđāļāļĩāđāļĒāļ§āđāļĄāļ·āļāļāđāļĨāļĒ
Pingback: āļāđāļāļāļĄāđāļāđ
Pingback: āļŠāļĨāđāļāļāđāļ§āđāļāļāļĢāļāļāļąāļāļāļąāļ 1
Pingback: Buy M1AâĒ STANDARD ISSUE .308 RIFLE â DESERT FDEÂ Online
Pingback: Buy BRNO 611 10 round .22WMR .17HMR magazine (ZKM 611/617)Â Online
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://accounts.binance.com/zh-CN/register?ref=IJFGOAID
Pingback: āļāļąāļāđāļāļīāđāļĨ
Pingback: āļāļēāļĢāđāļāļīāļĄāļāļąāļāļĄāļ§āļĒ āļāđāļāļāļāļĩāđāļāļ°āļĄāļĩ āđāļāļāļĄāļ§āļĒāļāļāļāđāļĨāļāđ
Pingback: āļāļąāļāļāļģāļŦāļāđāļēāļĒ āļāļļāļŦāļĢāļĩāđāđāļāļāđāļē
Pingback: āđāļ§āđāļāļāļāļąāļāđāļāļēāļŦāļĨāļĩ
Pingback: āļĢāļąāļāļāļģ SEO
Pingback: āļĨāļāļāļĢāļ°āļāļēāļĻāļāļēāļĒāļāđāļēāļāļāļĢāļĩ
Hello! I just would like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon.
Pingback: cream deluxe 666g n2o for sale | cream deluxe gold France | cream deluxe 666g prix | cream deluxe prix en gros | bonbonne cream deluxe pas cher | cream deluxe grossiste | fastgas nitrous oxide 640g for sale | smartwhip cream charger for sale | mosa cream
Pingback: saāļāļēāļŠāļīāđāļ
Pingback: geek bar frozen flavors
Pingback: āļŦāļąāļ§āļāļāļ Marbo
Pingback: Larry
Pingback: āđāļāđāļāļąāļ
Pingback: bundle extractor
I am constantly browsing online for ideas that can facilitate me. Thanks!
I am glad to be one of many visitors on this great internet site (:, appreciate it for putting up.
Pingback: Bmw historia
Pingback: āļĢāļąāļāļĐāļēāļŠāļīāļ§
Pingback: āļĢāļąāļāļāļ·āđāļāļāļĢāļ°āđāļāđāļēāđāļāļĢāļāļāđ
Pingback: āđāļāđāļāđāļāļāļāļąāļ§āļĢāđ
Pingback: pk789
Pingback: dark168
Pingback: som777
Pingback: āļŠāļĨāđāļāļāđāļ§āđāļāļāļĢāļ
I have read several good stuff here. Certainly worth bookmarking for revisiting. I surprise how a lot attempt you set to create this kind of great informative web site.
I have been examinating out a few of your articles and i must say pretty clever stuff. I will make sure to bookmark your website.
Nutr Cancer 1996; 26 1 111 20 Roller et al The antimicrobial activity of high necrodane and other lavender oils on methicillin sensitive and resistant Staphylococcus aureus MSSA and MRSA priligy dapoxetine 30mg Often ovulation is induced with the aid of medications