0

I am trying to have a button change it's styling based on it's current state.

This following is my current attempt:

<Button
    id="1W"
    size="sm"
    style={[this.state.timeSpan === '1W' ? btnActive : btnInactive]}
    onClick={this.handleSpan} 
>

Initially I was getting this error ->

"TypeError: CSS2Properties doesn't have an indexed property setter for '0' ".

Which I didn't know how to fix.

Now the page won't even load at all.

Is there something wrong with my syntax. Or possibly is there a better overall approach to what I trying to achieve?

phoenixson
  • 117
  • 10
  • I have answered based on the contents of `btnActive` and `btnInactive` to be CSS objects or class names. – Praveen Kumar Purushothaman May 05 '19 at 12:59
  • They are CSS objects that only exist in the JS file. So I don't know that className would have worked and therefore the Stackoverflow answer that you have suggested this question duplicates would not have worked for me. The answer you proposed has worked for me and if you repost it I can mark it as so. – phoenixson May 05 '19 at 13:57

2 Answers2

0

This is not the way you write the CSS, it's not a right syntax:

style={[this.state.timeSpan === '1W' ? btnActive : btnInactive]}

What you might do is, if it's an object with props:

style={(this.state.timeSpan === '1W' ? {...btnActive} : {...btnInactive})}

Or, if it's class names:

className={(this.state.timeSpan === '1W' ? btnActive : btnInactive)}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

I would say changing the element's class(es) is the preferred way:

<button 
  className={this.state.timeSpan == '1W' ? 'btnActive' : 'btnInactive'}
  ...>

That way, presentation is kept separate from logic as much as possible.


If the style is generated at run-time, then setting style is fine:

  ...
  style={this.state.timeSpan == '1W' ? btnActive : btnInactive}

(assuming btnActive is an object like eg. {color: 'rgb(1,2,3)'})

P Varga
  • 19,174
  • 12
  • 70
  • 108
  • I also have a line like that for changing it's class that takes care of it's sizing etc but I can't programmatically select 'non-predefined colors' that way... that I know off. – phoenixson May 05 '19 at 13:09
  • @phoenixson In that case you were close, just remove the `[]`s. Also added example to my answer – P Varga May 05 '19 at 13:17