Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Material UI condition statement within style property of button

I need to have a condition within style property of the button. Here is how my code look like at this moment.

  <Button variant="outlined" component="span" className={classes.button}>
    Choose file
  </Button>

I need to have condition something like this.

      <Button variant="outlined" component="span" className={classes.button}
style={{display: ((this.props.filename === true)? 'none' : 'block') }}
>
        Choose file
      </Button>

Any idea how can I make this work?

Ref: https://material-ui.com/api/button/

like image 821
Developer Avatar asked Jan 24 '19 22:01

Developer


2 Answers

You were very close. The only trick here is that by specifying === true in your condition will omit the type coercion on your variable, which is actually needed in this case as we want to check if the string is empty.

One fix for this would be to just remove it, and let JavaScript perform the type coercion, which checks if the string is empty or null:

<Button variant="outlined" component="span" className={classes.button} 
  style={{display: ((this.props.filename) ? 'none' : 'block') }}>
   Choose file
</Button>

This post explains well how the conversion is done. More ways of checking for empty string in JavaScript, with coercion or not, can be found in this SO post.

like image 56
Siavas Avatar answered Sep 30 '22 08:09

Siavas


I think the problem here is the same as described here: Can withStyles pass props to styles object?

like image 32
Valerii Avatar answered Sep 30 '22 08:09

Valerii