6

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/

Developer
  • 25,073
  • 20
  • 81
  • 128

3 Answers3

5

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.

Siavas
  • 4,992
  • 2
  • 23
  • 33
1

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

Valerii
  • 2,147
  • 2
  • 13
  • 27
0

Another approach is to create a separate classes: displayNone- when condition is met, and displayBlock-when not. Then use the clsx library to combine the two classes, like so:

      import clsx from "clsx"        
        <Button variant="outlined" component="span" 
    className={clsx(classes.button,this.props.filename? classes.displayNone:classes.displayBlock)}>
Choose file</Button>
NaE
  • 19
  • 1