Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react.js setState call with key but without value?

Just started to learn react.js and javascript. I'm going through all the documentation on facebook's github, but got stuck with this.

In the handleCelsiusChange method of Calculator class in Lifting state up chapter there is this line:

this.setState({scale: 'c', value});

So scale will get the value 'c'. Okay. But what is this value being simply there? Shouldn't it be a key-value pair? I've checked the explanation of setState():

The first argument can be an object (containing zero or more keys to update) or a function (of state and props) that returns an object containing keys to update.

But it says nothing relevant about this usage.

Thanks! :)

like image 969
inspiral Avatar asked Feb 11 '17 22:02

inspiral


1 Answers

That's actually a feature of ES6. If the key matches an existing variable name you can use this shorthand syntax. So instead of writing value: value you can simply write value as key and variable name are the same.

Example with ES6

function getCar(make, model, value) {
    return {
        // with property value shorthand
        // syntax, you can omit the property
        // value if key matches variable
        // name
        make,
        model,
        value
    };
}

The equivalent of the above in ES3/ES5

function getCar(make, model, value) {
    return {
        make: make,
        model: model,
        value: value
    };
}

Example taken from http://www.benmvp.com/learning-es6-enhanced-object-literals/

like image 63
Björn Kaiser Avatar answered Oct 06 '22 01:10

Björn Kaiser