One of the easiest ways to scroll to a React element is by using a mix of the useRef()
hook and the scrollIntoView()
API.
We will see how can we do this by building the below example:
We will start with a simple stateless component:
const App = () => {
return (<>
<p>scroll down a lot to see a red div āāā
<button onClick={doClick}>or click this button</button></p>
<div className="red">Red Div</div>
</>)
}
We will need to add the useRef() hook so that we can point to the targeted React element:
const App = () => {
const ref = useRef(null);
//...
<div ref={ref} className="red">Red Div</div>
}
With this in place, we can easily use the scrollIntoView API to bring that element into view.
ref.current?.scrollIntoView()
The full code is below and you can check out the working codepen here:
const App = () => {
const ref = useRef(null);
const doClick = () => ref.current?.scrollIntoView({behavior: 'smooth'})
return (<>
<p>scroll down a lot to see a red div āāā
<button onClick={doClick}>or click this button</button></p>
<div ref={ref} className="red">Red Div</div>
</>)
}
We can add some extra parameters to scrollIntoView()
like:
scrollIntoView({behavior: 'smooth'})
to add a natural animation the scroll movement- or
{block: "start", inline: "nearest"}
to set behaviors such as the top of the element to be aligned to the top of the visible area of the scrollable ancestor
Check out the full documentation here.
As a final thought when working with scrolling elements, you may also want to check out the Intersection Observer API in Javascript for performance improvements.
š Neural networks for Javascript developers
The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!