Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 821
Sammy Avatar asked Jul 07 '18 13:07

Sammy


People also ask

Can I use createRef in functional component?

createRef can be used in both class and functional components.

In which situation would you use refs in React?

Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all.

What is createRef in React?

Refs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component. class MyComponent extends React. Component { constructor(props) { super(props); this.

Can we pass ref as props?

There is one thing to consider, ref is not a prop. The reference passed to AwesomeButton , which is now a Higher-Order-Component, will not be passed down, because ref is not a prop. Instead, the reference will be attached to the HOC logProps .


1 Answers

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>
like image 51
Arman Charan Avatar answered Oct 10 '22 07:10

Arman Charan