blocker
blocker

Reputation: 105

Multiple state changes

I am following a lesson. I have a controlled form and a handleInput method to reflect any changes in input. However, I didn't understand why he writes [name] instead of name inside of the handleInput method. A detailed explanation will be appreciated.

 handleInput(event) {
        const target = event.target;
        const value = target.value;
        const name = target.name;

        this.setState({
            [name]: value
        })
    }

Form Structure:

<Form>
    <FormGroup>
        <Label htmlFor="firstname" md={2}>First Name</Label>
        <Input type="text" id="firstname" name="firstname" 
                                value={this.state.firstname} 
                                onChange={this.handleInput} />

    </FormGroup>
    <FormGroup>
        <Label htmlFor="lastname" md={2}>Last Name</Label>
        <Input type="text" id="lastname" name="lastname" 
                                value={this.state.lastname} 
                                onChange={this.handleInput} />
    </FormGroup>
</Form>

Upvotes: 1

Views: 68

Answers (5)

mxdi9i7
mxdi9i7

Reputation: 697

It's an ES6 feature, the square brackets allows you to programmatically reference the property of the object.

Upvotes: 1

Rajan Lagah
Rajan Lagah

Reputation: 2528

handleInput(event) {
        const target = event.target;
        const value = target.value;
        const name = target.name;
        // let name now = "blocker" and value = "something"
        this.setState({
            [name]: value
        })
    }

on console.log(this.state) output will be

{blocker:something}

Now if you remove [] from name

this.setState({
        name: value
    })

then on console.log(this.state) output will be

{name:something}

Upvotes: 0

sudo bangbang
sudo bangbang

Reputation: 28229

In the form, the input elements has names. In handleInput function, when you do

const name = target.name;

This name gets assigned to name

Now, on doing

this.setState({
        [name]: value
})

name gets evaluated to firstname or lastname.

You can read more about this feature here

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55750

This syntax is for computed property name

Its a new ES6 feature which computed the property name of the object.

Before this you had to specify the property directly on the object.

var data = {};
data[name] = value;

this.setState(data);

With the new syntax you can do it inline with the object definition.

this.setState({
  [name]: value
})

Upvotes: 1

Jake
Jake

Reputation: 742

Declaring the key in state as just name: value would reference an object key in state actually named name. Instead using [name] references the value of name attained from the input (const name = target.name;) which will in turn reference the corresponding key in the state.

Upvotes: 0

Related Questions