I am trying to add the following ternary operator to show my button if I am logged in and If I am not to hide it. The following below keeps throwing me an error.
<img src={this.state.photo} alt="" style="{isLoggedIn ? 'display:' : 'display:none'}" />
You can use the ternary operator to configure dynamic classes in React. It is a short and simple syntax. First, you must write a JavaScript expression that evaluates true or false , followed by a question mark.
There are almost endless ways to style a component in React, but using the HTML style element is one of the most creative and unusual. This approach allows you to use raw CSS while reducing your styled component definition to just one file.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
What you provide to style attribute should be an object. Since we write js code in jsx between curly braces, you ll insert an object there.
Remember, you need to camelCase all css props. ( font-size ==> fontSize )
<img src={this.state.photo} alt="" style={ isLoggedIn ? { display:'block'} : {display : 'none'} } />
or
<img src={this.state.photo} alt="" style={ { display: isLoggedIn ? 'block' : 'none' } } />
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