I'm trying to set a state that I'm getting from an input target:
Below is the code for my constructor and the method which updates the target's state
constructor(props) {
super(props);
this.state = {
title: ''
};
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.setState({
[e.target.name] : e.target.value
});
}
Where the input is given by this code:
<input type={"text"} name={"title"} value={this.state.title} onChange={this.onChange}/>
When I debug my code I found that e.target.name contains "title" and I do not understanding why I need the squared brackets []
in [e.target.name]
... I found some explanation on the web but I have not understood what it means:
We use attr in this.setState with square brackets [ ] because [ ] lets us query object key names programmatically (similar to how array[2] or object[keyA] works)
Can you help me to understand why we need these brackets ?
FYI : If I remove the brackets as this :
onChange(e) {
this.setState({
e.target.name : e.target.value
});
}
this give me this error : "Unexpected token, expected" at e.target.name
The square bracket is used to get the name of the event target and set the value to the state. For example, if the email field is changed - it fetches the email value and sets it to the state (state object/email value) and does the same to the password as well.
Square brackets are used to index (access) elements in arrays and also Strings. Specifically lost[i] will evaluate to the ith item in the array named lost.
import React, { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); We declare a state variable called count , and set it to 0 .
Changing the state Object To change a value in the state object, use the this. setState() method. When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s).
This syntax is just another way to set a key of an object without knowing ahead of time what you want it to be called -- a computed property name.
For instance, these two examples accomplish the same thing:
const myNewObject = {
name: 'Joe',
age: 30
}
…
const propName = 'age'
const myNewObject = {
name: 'Joe',
[propName]: 30
}
So in your example– e.target.name
comes from the name
attribute of the input element ("title", in this case). By setting the state's key with [e.target.name]
you're really just setting the title
property of the state.
{ sth: else }
is equal to
{ ["sth"]: else }
or
var id = "sth";
{ [id]: else }
So you basically need it when you want to evaluate the identifier instead of taking it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With