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
Date.Setmonth' Causes the Month to Be Set Too High If 'Date' Is at the End of the Month
Pass Value to Iframe from a Window
How to Break Nested Loops in JavaScript
Mongoose Find/Update Subdocument
Extending Built-In Natives in Es6 with Babel
Convert Js Object to Form Data
What's the Difference Between JavaScript and Jscript
Failed to Execute 'Createobjecturl' on 'Url':
Generate Unique Number Within Range (0 - X), Keeping a History to Prevent Duplicates
JavaScript Getelementbyid() Not Working
How to Do a Deep Comparison Between 2 Objects with Lodash
Semicolon Before Self-Invoking Function
JavaScript Accessing Inner Dom of Svg
JavaScript Change Date into Format of (Dd/Mm/Yyyy)
Why the Function Called by Settimeout Has No Callstack Limit
Differencebetween Parseint(String) and Number(String) in JavaScript