How to style elements from componentDidMount?

4.6k views Asked by At

I have a component:

  render: function () {
    const item = this.props.item
    return (
            <div style={{marginTop: '20px', display: 'flex'}}>
              {item.get('images').map((url, i) =>
                  <Thumbnail href='#' src={stripUrl(url)} onClick={() => this.flky.select(i)} />
    ´          )}
            </div>
    ´    )
  }

In componentDidMount, I wish to target one of the thumnails and update it's style, I know what index the thumbnail has, how can I do this?

  componentDidMount: function () {
    this.flky = new Flickity('.carousel', flickityOptions)
    this.flky.on('select', () => {
      console.log('Flickity settled at ' + this.flky.selectedIndex)
    })
  }
2

There are 2 answers

0
Ahmed Ali On

You can do that using state variable for example

// constructor
this.state = { mounted: false };

// componentDidMount
this.setState({ mounted: true });

// render 
<View style={ this.state.mounted ? styles.style1 : styles.style2 ></View>
0
Marco Scabbiolo On

You can't directly change how the component is rendered, all you can do is modify its state or its properties, you would have to set some property of the state and render accordingly in the render method.

Set a property in the original state like thumbnailIndex to -1 for example

getInitialState: function () {
  return {
    thumbnailIndex: -1
  };
}

When you render the thumbnails check for it to match the current index

<Thumbnail 
  href='#' 
  style={this.state.thumbnailIndex === i ? { ...styles... } : undefined} 
  ... 
/>

On componentDidMount set the index in the state

this.setState({ thumbnailIndex: this.flky.selectedIndex });