Articles → REACT.JS → Manage Multiple States Using A Single Object In React.Js

Manage Multiple States Using A Single Object In React.Js






Example


import ReactDOM from 'react-dom'
import { useState } from 'react';


const Home = () => {

    const [userInput, setUserInput] = useState({
        name: '',
        email:''
    })

    const handleClick = () => {        
        alert(userInput.name + "***" + userInput.email) ;
    }

    const nameChangeHandler = (event) => {
        setUserInput({
            ...userInput,
            name : event.target.value,
        });
    }

    const emailChangeHandler = (event) => {
        setUserInput({
            ...userInput,
            email: event.target.value,
        });
    }

    return (
        <form>
            <div>
                Name:
                <p><input type="text" name="nameField" onChange={ nameChangeHandler}/></p>
                Email:
                <p><input type="text" name="emailField" onChange={emailChangeHandler}/></p>
                <button onClick={handleClick}>Click me</button>
            </div>
        </form>
    );
}

ReactDOM.render(<Home />, document.getElementById('root'));



Output


Picture showing how to manage multiple states using a single object in react.js
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Friday, September 3, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250