user1072337
user1072337

Reputation: 12935

How to enact styles with React.js

I am trying to use inline styles with React.js, but I keep running into errors:

In my render function, I have:

render: function() {
    var style = this.state.submitted ? {{"backgroundColor": "#1abc9c", "opacity": "0.6"}} : {{}}; 
    return (
      <div>

        <h1 className="home-two-question" style={style}>{text}</h1>

      </div>
    )
  },

Basically I want to toggle this style on click. However, when I run this, I get an error from React.js. What is the correct syntax for inline styles in React.js? Thank you!

Upvotes: 1

Views: 175

Answers (1)

Xymostech
Xymostech

Reputation: 9850

In this line:

var style = this.state.submitted ? {{"backgroundColor": "#1abc9c", "opacity": "0.6"}} : {{}};

you're just in plain JavaScript, not inside of a JSX tag. Thus, you just want to use single {}, not double {{}}:

var style = this.state.submitted ? {"backgroundColor": "#1abc9c", "opacity": "0.6"} : {};

In particular, when you do something like:

<div style={{"backgroundColor": "white"}}>

There is one set of {} to denote that the value of the style prop should be interpreted as JavaScript, and another set of {} to denote that you are constructing an object within that value.

Upvotes: 4

Related Questions