Borislav Hadzhiev
Sun Apr 24 2022·2 min read
Photo by Lua Valentia
To scroll to an element on click in React:
ref
prop on the element you want to scroll to.onClick
prop on the other element.scrollIntoView()
method on the
ref
object.import {useRef} from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { ref.current?.scrollIntoView({behavior: 'smooth'}); }; return ( <div> <button onClick={handleClick}>Scroll to element</button> <div style={{height: '155rem'}} /> <div ref={ref}>Some content here</div> <div style={{height: '155rem'}} /> </div> ); }
We initialized a ref using the useRef hook.
The useRef()
hook can be passed an initial value as an argument. The hook
returns a mutable ref object whose .current
property is initialized to the
passed argument.
current
property on the ref object to get access to the div
element on which we set the ref
prop.When we pass a ref prop to an element, e.g. <div ref={myRef} />
, React sets
the .current
property of the ref object to the corresponding DOM node.
We set the onClick
prop on the button element, so every time it's clicked, the
handleClick
function is invoked.
const handleClick = () => { ref.current?.scrollIntoView({behavior: 'smooth'}); };
In the handleClick
function, we used the
scrollIntoView
method to scroll to the div
element on which the ref
prop is set.
behavior
property specifies whether the scrolling should animate smoothly (smooth
), or happen instantly (auto
).The default value for the behavior
property is auto
.
Every time the button is clicked, the scrollIntoView()
method is invoked on
the element on which we set the ref
prop, and the element is made visible to
the user.