0

In a React sample app I've seen this:

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {temperature: '', scale: 'c'};
  }

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

It isn't clear to me how this line of code works:

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

The state is defined in the constructor like a JSON object:

this.state = {temperature: '', scale: 'c'};

where it has a "temperature" and a "scale" field. But setState is called, the scale member is specified along with the value. But the temperature field's name is not specified. Only its value. Is this a Javascript thing or a React thing? I'm not used to seeing a field's value specified without the field's name. How is React or Javascript suppose to know what field to apply the temperature value to?

Johann
  • 27,536
  • 39
  • 165
  • 279
  • 1
    Its and ES2015 thing, known as [Shorthand property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions) – Nick Parsons Mar 02 '20 at 08:43
  • I reviewed the links but it isn't clear with the example I gave. So if I understand it, you can leave off the field name as long as the name of the value you are applying (in my case "temperature") is the same as the field's name. – Johann Mar 02 '20 at 08:50
  • essentially, take: `{temperature: temperature}` this is an object which has `temperature` as the _key_ and uses the value stored in the _variable_ temperature as the value. The notice how the variable name for `temperature` is the same as the key in the object, if this is the case, you can use `{temperature}` which is short-hand for `{temperature: temperature}` – Nick Parsons Mar 02 '20 at 08:54
  • 1
    So for this to work, the name of the key and the name of the variable holding the value must be the same name. – Johann Mar 02 '20 at 08:54
  • yes, that is correct. eg: const foo = "abc", `{foo}` would create a key named _foo_, with the value of `"abc"`, so `{foo: "abc"}` – Nick Parsons Mar 02 '20 at 08:57

0 Answers0