0

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
 }}

1 Answer 1

1

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' }
  }}
/>
1
  • I was thinking if you could do it straight in the style attribute in the rendering, updating question.
    – Himmators
    Commented Dec 27, 2016 at 1:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.