Sometimes, we want to scroll to an element in a React component.
In this article, we’ll look at how to scroll to an element in a React component.
Scroll to an Element in a React Component
We can scroll to an element by assigning a ref to it and calling scrollIntoView
on it.
For instance, we can write:
import React, { useRef } from "react";
export default function App() {
const myRef = useRef(null);
const executeScroll = () => myRef.current.scrollIntoView();
return (
<>
<button onClick={executeScroll}> Click to scroll </button>
{Array(100)
.fill()
.map((_, i) => (
<p>{i}</p>
))}
<div ref={myRef}>Element to scroll to</div>
</>
);
}
We create myRef
with the useRef
hook,
Then we create the executeScroll
method that calls scrollIntoView
on the element that’s been assigned the ref.
myRef.current
has the element we assigned the ref to as its value.
We assign the ref by assigning the ref
prop with myRef
.
Then we set the onClick
prop to executeScroll
to run executeScroll
when we click on the button.
Now when we click on the button, we should scroll to the element that’s assigned to myRef
.
Conclusion
We can scroll to an element by assigning a ref to it and calling scrollIntoView
on it.