Browser APIs Available for Scrolling
Browsers largely support a few different methods of scrolling to different parts of the page using native APIs.
The ones we’ll cover include:
<button onClick={() => {
const element = document.getElementById('my-section');
element?.scrollIntoView({
behavior: 'smooth'
Jump to My Section
</button>
This can be particularly handy if you’re propagating events to a parent element or if the data is loading dynamically making it challenging to add a ref to every instance.
Part 2: Scrolling to the Top of the Page with scroll & scrollTo
Scrolling to the top of the page isn’t necessarily an element, but it’s a location on the page that’s typically marked by an element.
Historically, one way of providing a “Jump to Top” link was to use an anchor link and a fragment, which works well, but requires a little extra markup.
That works according to spec :
<button onClick={() => {
const element = document.getElementById('my-section');
if ( !element ) return;
window.scroll({
top: element.offsetTop - 20,
behavior: 'smooth'
Jump to My Section
</button>
Removing 20 gives us a nice little bit of padding before the element so the header isn’t completely hugging the top of the page.