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?
createRef can be used in both class and functional components.
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.
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.
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 .
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With