Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 614
Henrik Petterson Avatar asked Jun 17 '19 13:06

Henrik Petterson


People also ask

How to add common style in React components?

Now the common style file is added to the “index.html” page. 2. Inline Style in React Component One of the easiest ways to add style to the React Components is to add it inline to the elements in the component. We can add style directly to the element using the “style” attribute.

What are inline styles in react?

Inline styles are not react specific They are a regular HTML feature: However, we have to use it a little bit differently in react. Instead of passing a string with all the styles to the attribute, we need to assign an object:

How to conditionally add attributes to React components?

We can conditionally add attributes to React components with the following approaches: Evidently, with some attributes, React is smart enough to omit the attribute if the value you pass to it is not truthy. For example: Above Syntax will result in the following output:

What are style files in react?

The style files added are the part of the React “src” folder itself rather than being a part of the “public” folder. Style Files are divided into sub-parts on the basis of components We can have small styling as per each component. Style files can be imported dynamically when a component is required


1 Answers

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>
like image 136
R3tep Avatar answered Oct 13 '22 19:10

R3tep