I have some generic code that attempts to update specific states. It's possible to access an object by the keys in an array, e.g:
let x = {person: { name: "Dennis"}}
console.log(x["person"]["name"])
In react, it is possible (and often used in input validation), to access a specific state-key by array, e.g:
//event.target.name = input field property name="firstName"
this.setState({
[event.target.name]: event.target.value
});
Which would update this.state.firstName
to the inputs value.
I am trying to bind nested complex objects to inputs, to avoid having translation functions. So if my state contains { person: {name : "" } }
I want to access it dynamically by this.state["person"]["name"] - which works. I want to use the same notation in setState
, because then I can bind my nested state-data to inputs like this: <input name="person.name" />
and in my change handler I can look for periods: if(ev.target.name.split("."))...
However, I can't seem to access the state in the same way in setState, because it's an object, so:
const args = ev.target.name.split(".");
this.setState({
[args[0]][args[1]]: ev.target.value
});
Is there anyway to do this?