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' }
  }}
/>
Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking if you could do it straight in the style attribute in the rendering, updating question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.