Victor Lin Victor Lin - 1 month ago 11
CSS Question

Does ReactJS parse object literals into strings?

I am walking through the ReactJS tutorial right now, mulling over the section 'Thinking In React', and in particular an aspect of the code really bothers me:

class ProductRow extends React.Component {
render() {
var name = this.props.product.stocked ?
this.props.product.name :
<span style={{color: 'red', background: 'green'}}> // this line
{this.props.product.name}
</span>;
return (
<tr>
<td>{name}</td>
<td>{this.props.product.price}</td>
</tr>
);
}
}


For the rest of the code, see: http://codepen.io/lacker/pen/vXpAgj

... at line 11, style is assigned {color: 'red'}. In my head, this shouldn't work, because it doesn't conform to the styling syntax (e.g. "color: 'red'"). Yet, if I replace curly braces with double quotes, the code doesn't run.

1) Is there an ES6/JSX/React rule that converts object literals to the double quote format? (How does this work?)

2) Why wouldn't replacing the curly brackets with double quotes work? (Tried it on codepen)

Thank you!

Answer

As mentioned in the documentation, the style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. So if you replace it with quoted string, it wouldn't work.

They choose this approach because this is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.

Note that style name are camelCased rather than dash-separated. i.e. marginLeft rather than margin-left.