kaushik
kaushik

Reputation: 556

Conditional inline style in react js

I want to hide the button if this.state.task.status == 'Completed'(Like adding display: none property)

Code:

<Button size="small"           
style={{display:this.state.task.status == "Completed" ? "none":""}}              
style={textColor} >Mark as Completed</Button>

textColor is another style which is working fine.

Upvotes: 3

Views: 17026

Answers (2)

Matthew Herbst
Matthew Herbst

Reputation: 31973

You only want to pass a single style prop to a component. By passing two, the second one is overriding the first one, causing your display style to never make it to the styles:

<Button
  size="small"           
  style={{
    display: this.state.task.status == "Completed" ? "none": "",
    textColor,
  }}              
>
  Mark as Completed
</Button>

I support @MRchief's answer as well: in React, if you don't want to show an element, you shouldn't render it, unless you specifically need it hidden on the page for some reason (such as a hidden input).

Upvotes: 10

Mrchief
Mrchief

Reputation: 76208

You can do this:

<div>
{ this.state.task.status == "Completed" && (<Button size="small" style={textColor} >Mark as Completed</Button>) }
</div>

Upvotes: 2

Related Questions