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?
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.
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:
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:
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
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With