In the following code (it's a button that changes the color when you click), I don't understand why I need curly braces {} on line9 and 14 but not on line13.
On line 13, we affect state colorGreen to the state color and curly braces are required to read colorYellow variable so we use JS. Am I correct ? On line 14 it is the same. On line 13, it is the same, we use colorGreen and color Yellow variable but we don't need curly brace ? Why ?
Thank you
var React = require('react');
var ReactDOM = require('react-dom');
var colorGreen = '#39D1B0';
var colorYellow = '#FFD710';
var Switch = React.createClass({
getInitialState: function () {
return { color: colorGreen }; //line9
},
changeColor: function () {
var changeColor = this.state.color == colorGreen ? colorYellow : colorGreen; //line13
this.setState({ color: changeColor }); //line14
}
});
They're just plain object literals of JavaScript, not any special syntax of React.
You can create an object in JavaScript by:
var obj = {
foo: 'bar'
}
and in your code:
return {
color: colorGreen
}
means create an object and return it immediately.
Please see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer