6

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?

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

3 Answers3

5

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>
R3tep
  • 12,512
  • 10
  • 48
  • 75
3

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" }}>
Kobe
  • 6,226
  • 1
  • 14
  • 35
0

If you try this, it will work:

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

You should write it with camelCase.

font-weight => fontWeight

Erçin Dedeoğlu
  • 4,950
  • 4
  • 49
  • 69