Himmators
Himmators

Reputation: 15006

Conditionally apply single attribute in react?

Is there a shorter/inline version of doing this in react, basically applying a single css attribute conditionally?

  setStyle () {
    const style = {
      display: 'flex',
      flexDirection: 'column',
      height: 485
    }
    if (this.state.zoom) {
      style.position = 'absolute'
    }
    return style
  }

  <div ref='container' style={this.setStyle()}>

Something in this context:

style={{
   display: 'flex',
   flexDirection: 'column',
   height: 485
   position: absolute // Make this conditional
 }}

Upvotes: 0

Views: 65

Answers (1)

azium
azium

Reputation: 20614

Using Object.assign

let style = Object.assign({
  display: 'flex'
}, this.state.zoom && { position: 'absolute' })

Using spread/rest properties

let style = {
  display: 'flex',
  ...this.state.zoom && { position: 'absolute' }
}

Inline, inline:

<div
  style={
    Object.assign({
      display: 'flex'
    }, this.state.zoom && { position: 'absolute' })
  }
/>

<div
  style={{
    display: 'flex',
    ...this.state.zoom && { position: 'absolute' }
  }}
/>

Upvotes: 1

Related Questions