Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator on style with React Js Es 6

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'}"  /> 
like image 444
user992731 Avatar asked Dec 12 '16 00:12

user992731


People also ask

Can we use ternary operator in React JS?

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.

Can we use style tag in React JS?

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.

Can we use ternary operator in JavaScript?

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.


1 Answers

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' } }   /> 
like image 80
FurkanO Avatar answered Sep 21 '22 14:09

FurkanO