Victor Lin Victor Lin - 1 year ago 126
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 ? :
<span style={{color: 'red', background: 'green'}}> // this line
return (

For the rest of the code, see:

... 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download