1

Having this 2 scenarios for handling inline styles, which one is the ideal way to 'toggle' CSS properties depending on the component state - or is a better one?

1. Create a style variable in which you query for the component's state to make a decision, this way you use only one object when assigning the style in your JSX. see it working here - also this method is not addressed in this top question

render(){
    const style = {
      pStyle : {
        borderRadius: this.state.isCircle ? '50%' : '0px', //query the current state
        height: this.state.isCircle ? '100px' : 'auto', //query the current state
        display: 'inline-block',
        width: '100px',
        textAlign: 'center',
        transition: 'all 0.5s ease-in-out',
        border: 'solid 2px lightblue'
      }
    }
    return(
      <div>
        <p style={style.pStyle} onClick={this.HandleClick}>Hi!</p>

      </div>
    )
}

2. Create more than one object to represent each CSS state of your component, this way you will have to query for the component's state in your JSX and merge the objects with ES6's Object.assign. see it working here

render(){
    const style = {
      pStyle : {
        display: 'inline-block',
        width: '100px',
        textAlign: 'center',
        transition: 'all 0.5s ease-in-out',
        border: 'solid 2px lightblue'
      }, 
      pStyleCircle : { //this will only be applied when state is Circle
        borderRadius: '50%',
        height: '100px',
      }
    }
    return(
      <div>
        <p style={Object.assign({},style.pStyle, this.state.isCircle && style.pStyleCircle)} onClick={this.HandleClick}>Hi!</p>
      </div>
    )
  }

both ways work, but which one should be used over the other, and why?

Carlos Valencia
  • 6,499
  • 2
  • 29
  • 44

1 Answers1

1

I don't think there's a proper way to do it. You've a lot of variables here.

In my personal and honest opinion I would say the second one is easier to understand and fairly more maintainable and even though I don't like to work with inline style, I would've done something similar with CSS and different modifier classes with just the necessary props.

Just for the record, you can do the same with CSS and classnames.