Search code examples
reactjscss-animationsjs-scrollintoview

Triggering imperative animations using React Refs


from the documentation, there's this use case for Refs:

Triggering imperative animations.

Can someone offer an example on how this should be done please? I'm trying to bring the user attention to a div after having scrolled it into view using its Ref and I think this would be an ideal use case, maybe?


Solution

  • See Refs and the DOM, EventTarget.addEventListener(), and Element.getBoundingClientRect() for more info.

    // Imperative Animation
    class ImperativeAnimation extends React.Component {
    
      // State.
      state = {background: '#fff'}
    
      // Render.
      render = () => (
        <div ref={this.divRef} style={{height: '200vh', background: this.state.background}}>
          Scroll to turn background papayawhip.
        </div>
      )
      
      // Did Mount.
      componentDidMount() {
        window.addEventListener('scroll', this.onScroll)
      }
      
      // Div Ref.
      divRef = React.createRef()
      
      // On Scroll
      onScroll = event => {
        const div = this.divRef.current
        const {y} = div.getBoundingClientRect()
        if (y <= 0) this.setState({background: 'papayawhip'})
        else this.setState({background: '#fff'})
      }
      
    }
    
    // Mount.
    ReactDOM.render(<ImperativeAnimation/>, document.querySelector('#root'))
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <div id="root"></div>