Update object State || Form inputs value || React 18

Update object State || Form inputs value || React 18 – In the React state update for object default values from form inputs values, it’s an easy process to do.

How to update react object state like form inputs values

Before updating object values you may have this type of default values setup.

const [values, setValues] = useState(
        {
            userName:'',
            email:'',
            date:'',
            password:'',
            confirmPassword:'',
        }
    );

and it needs to update after changes on input fields.

onChange={onChange} method.

const onChange = (e) => {
      
        setValues({...values, [e.target.name]: e.target.value})
    }

this on change method you need to add this simple code to update your old object state value into React.

setValues(
            {
            ...values, 
            [e.target.name]: e.target.value
        })

Here is the definition.

setValues() is the default that you may know.

inside the setValue function has object {} like this curli braces

first inside the object has added old values

old values should be like

userName:”,

email:”,

date:”,

password:”,

confirmPassword:”,

etc. and in this list or array has an index

as per the following index use

[e.target.name] and in this index assign the input value of form e.target.value

[e.target.name] will find the old value and assign the new input value.

Leave a Reply