usestate in object 1

usestate in object

- Through Input

        const [state, setState] = useState({ fName: "", lName: "" });
        const handleChange = e => {
            const { name, value } = e.target;
            setState(prevState => ({
                ...prevState,
                [name]: value
            }));
        };

        
        
   ***************************

 - Through onSubmit or button click
    
        setState(prevState => ({
            ...prevState,
            fName: 'your updated value here'
         }));

Here is what the above code is Doing:
1. We’re creating a state variable called state and a function to update it called setState.
2. We’re setting the initial state to an object with two properties: fName and lName.
3. We’re creating a function called handleChange that takes an event object as a parameter.
4. We’re using the event object to get the name and value of the input that was changed.
5. We’re using setState to update the state object with the new value.
6. We’re passing the handleChange function to the onChange attribute of each input.
7. We’re setting the value of each input to the corresponding state property.

Similar Posts