React update nested objects with input name

92 Views Asked by At

Lets imagine we have the following state:

const [sample,setSample] = useState({
    key:{
        value:'',
        otherValue:''
    }
});

Now we all know that if we use name=key on an input like this:

<input name="key" value={key} .../>

we can change the "key" property with:

 set sample({...sample,[e.target.name]:e.target.value});

But I was wondering, could we expand this a bit further to be used with nested state. What if we use name=key.value to change the "value" or "otherValue" property under "key" like this:

<input name="key.value" value={key.value} .../>

But in this case, it just creates a key with the name "key.value" to the state, which is not what we want.

I found this method what is the best way to setState which contains nested Object but I found that solution to be a little brute force and not that elegant.

Is there any way to make this work without brute forcing it? (What if nesting values could vary?)

1

There are 1 best solutions below

0
Lansana Diomande On

If you want, you can try react-hook-form to resolve your problem.

See some exemple here to use register with nested : https://react-hook-form.com/docs/useform/register