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?

2
  • Should be <p style={{color:"#DF0101", fontWeight:"bold"}}> Commented Jun 17, 2019 at 13:24
  • Possible duplicate of React.js inline style best practices Commented Jun 17, 2019 at 14:57

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Still did not work, here is my exact code. Am I missing something?
His code is completely fine. See here
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" }}>

3 Comments

Still did not work, here is my exact code. Am I missing something?
This code works for me. Are there any errors in your console?
Check this repl.it @HenrikPetterson
0

If you try this, it will work:

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

You should write it with camelCase.

font-weight => fontWeight

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.