Reactjs Setstate() with a Dynamic Key Name

react setState with dynamic key

Basic rule is:

We can use Computed property names concept and use any js expression to compute the object property name dynamically. For that we need to put the expression inside [].

Like this:

var obj = {   [10 * 20 + 1 - 5]: "Hello"};
console.log('obj = ', obj);

Best way to set state of object using dynamic key name? - reactjs

We can use Computed property names concept to compute the object property name dynamically. For that we need to put the expression inside [].

When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

For your state

this.setState({
formInput: {
...this.state.formInput,
[event.target.name]: event.target.value
}
})

Sandbox for your reference: https://codesandbox.io/s/react-basic-example-p7ft8

import React, { Component } from "react";

export default class Login extends Component {
state = {
formInputs: {
email: "",
password: ""
}
};

handleOnChange = event => {
this.setState({
formInput: {
...this.state.formInput,
[event.target.name]: event.target.value
}
});
};

render() {
return (
<form>
<label>Email</label>
<input type="text" name="email" onChange={this.handleOnChange} />
<label>Password</label>
<input type="password" name="password" onChange={this.handleOnChange} />
</form>
);
}
}

Set state using dynamic key in React hook

Instead of State it will become:

const [state, setState] = useState({});

you can invoke setState like this:

setState({ [e.target.name]: e.target.value });

Update state using dynamic key and value by using react hooks

Worked by the following solution

 const arrayList = viewRecordCount;
arrayList.push({ [viewId]: response.data.viewResultCount })
setViewRecordCount({ records: arrayList })

Using a dynamic key to setState in React

When setting state with a dynamic key, you need to wrap the key within [] like

<Modal
onTextChange={(text, key) => {
this.setState({
event: {
[key]: text
}
})
}}
/>


Related Topics



Leave a reply



Submit