Henrik Petterson
Henrik Petterson

Reputation: 7104

Adding style attribute in react

In react, have this:

return (
   <tag>
     { variable ? 
            <p> hello </p>
        :
            <p> world </p>
     }
   </tag>
)

As you can see, I am doing a ternary operator to output content depending on variable. I want to add style attribute in the p tag, like this:

<p style="color:#DF0101;font-weight:bold;"> hello </p>

But it doesn't work. I also tried:

<p style={{color:"#DF0101", font-weight:"bold"}}>

What am I doing wrong?

Upvotes: 6

Views: 1911

Answers (3)

R3tep
R3tep

Reputation: 12864

It's not font-weight but fontWeight, you need to use camelCase notation

 <p style={{color:"#DF0101", fontWeight:"bold"}}>

Ref

The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string.


Update based on comments

There is a logic error in your example code. The css are not updated, only the text. So use the ternary to change the text.

 <p style={{ color:"#DF0101", fontWeight:"bold" }}> 
   {{ lockPost === true ? 'Not ready' : 'Ready!' }} 
 </p>

Upvotes: 5

Er&#231;in Dedeoğlu
Er&#231;in Dedeoğlu

Reputation: 5383

If you try this, it will work:

<p style={{color:"#DF0101", fontWeight:"bold"}}>

You should write it with camelCase.

font-weight => fontWeight

Upvotes: 0

Kobe
Kobe

Reputation: 6456

You cannot have dashes in a JS variable (or key, in this case). You want to use your second example, but replace all dashes with camelCase, like this:

<p style={{ color:"#DF0101", fontWeight:"bold" }}>

Upvotes: 3

Related Questions