Conditional inline style in react js

11,436

Solution 1

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).

Solution 2

You can do this:

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

Related videos on Youtube

kaushik
Author by

kaushik

Software Engineer

Updated on May 28, 2022

Comments

  • kaushik
    kaushik almost 2 years

    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.