What is useState() & how it has been used to validate input values? - GeeksforGeeks

13 Oct, 2021
The useState() is a hook in ReactJs which allows a functional component to have a state. We pass the initial state in this function, and it returns us a variable and a function to update that state.
We have to import the useState() hook from the react package.import  { useState } from 'react';
We have to import the useState() hook from the react package.
import  { useState } from 'react';
Syntax to create state using useState() hook:const [ state, updateState] = useState("Initial Value")
Syntax to create state using useState() hook:
const [ state, updateState] = useState("Initial Value")
The useState() returns a list with two-element. first is the state itself, and the second is the function to update this state.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder, i.e., foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example 1:Filename App.js:
Javascript
import React, { Component, useState } from "react";const App = () =>   {      const [name, updateName] = useState("kapil")const handleUpdate = () => {        updateName("Nikhil")}    return(    <div >      <button        style = { {margin: 100 }}        onClick = { () => { handleUpdate()} } >        change Name      </button>      { name }    </div>    );            }export default App;
Output:
Example 2: Validation of Input value in React allows an error message to be displayed if the user has not filled out the form with the expected value. There are many ways to validate input value with React. 
Filename App.js:
Javascript
import React from 'react';  export default class App extends React.Component {            state = {        fields: {},        errors: {}    }    //method to validate values     handleValidation = ()=>{      let fields = this.state.fields;      let errors = {};      let formIsValid = true;        //Name check if name is empty or not      if(!fields["name"]){         formIsValid = false;         errors["name"] = "Cannot be empty";      }        //name should not contain special char      if(typeof fields["name"] !== "undefined"){         if(!fields["name"].match(/^[a-zA-Z]+$/)){            formIsValid = false;            errors["name"] = "Only letters";         }              }         //Email should not be empty      if(!fields["email"]){         formIsValid = false;         errors["email"] = "Cannot be empty";      }        //validating email      if(typeof fields["email"] !== "undefined"){         let lastAtPos = fields["email"].lastIndexOf('@');         let lastDotPos = fields["email"].lastIndexOf('.');           if (!(lastAtPos < lastDotPos && lastAtPos > 0         && fields["email"].indexOf('@@') == -1 &&          lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {            formIsValid = false;            errors["email"] = "Email is not valid";          }     }         this.setState({errors: errors});     return formIsValid; }      //after submit form it will be called  handleSubmit = (e) =>{  e.preventDefault();    if(this.handleValidation())      alert("form submitted successfully")  }      //updating the field value  handleUpdate(field, e){             let fields = this.state.fields;    fields[field] = e.target.value;            this.setState({fields});}           render(){      return (          <div style = {{margin:200}}>                        <form  onSubmit= {this.handleSubmit.bind(this)}>                 <input  type="text"  placeholder="Name"                  onChange={this.handleUpdate.bind(this, "name")}                  value={this.state.fields["name"]}/>                    <span style={{color: "red"}}>                    {this.state.errors["name"]}</span>                    <br/>                 <input type="text" placeholder="Email"                  onChange={this.handleUpdate.bind(this, "email")}                  value={this.state.fields["email"]}/>                    <span style={{color: "red"}}>                    {this.state.errors["email"]}</span>                    <br/>                 <button type = "submit">click</button>                  </form>          </div>    )  }}
Output:
kashishsoda
Picked
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components