How To Scroll To An HTML Element In NextJS?
Last Updated :
03 Jun, 2024
NextJS has various features that enable smooth scrolling to HTML elements. One method involves using useRef to create a reference to the target element and scrollIntoView to achieve smooth scrolling. Another method, using useEffect and window.scrollBy, sets up an event listener on a button for smooth scrolling when clicked, with useRef hooks to reference elements.
Prerequisites
Below are the approaches to scroll to an HTML element in NextJS:
Steps to Setup a NextJS App
Step 1: Create a NextJS application using the following command and answer a few questions.
npx create-next-app@latest app_name
Step 2: It will ask you some questions, so choose as the following.
√ Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? ... Yes
√ Would you like to customize the default import alias (@/*)? ... No
Step 3: After creating your project folder, move to it using the following command.
cd app_name
Project Structure

The updated dependencies in package.json file will look like:
"dependencies": {
"next": "13.5.6",
"react": "^18",
"react-dom": "^18"
},
In this approach, we are using the useRef hook to create a reference to the target element and the scrollIntoView method to smoothly scroll to this element. When the button is clicked, the scrollToElement function is triggered, causing the page to scroll to the element referenced by geeksForGeeksRef.
Example: The below example demonstrates the scolling to an HTML element using ref and scrollIntoView.
JavaScript
// page.js this is the entry point of application
"use client";
import { useRef } from 'react';
const App = () => {
const geeksForGeeksRef = useRef(null);
const scrollToElement = () => {
if (geeksForGeeksRef.current) {
geeksForGeeksRef.current.scrollIntoView({ behavior: 'smooth' });
}
};
return (
<div style={{ padding: '20px' }}>
<h3>Approach 1: Using ref and scrollIntoView</h3>
<button onClick={scrollToElement}
style={{ marginBottom: '20px' }}>
Scroll to GeeksforGeeks
</button>
<div style={{ height: '100vh' }}></div>
<h1 ref={geeksForGeeksRef}
style={{ color: 'green' }}>
GeeksforGeeks
</h1>
</div>
);
};
export default App;
Start your application using the following command.
npm run dev
Output:

In this approach, we are using useEffect to set up an event listener on the button, which triggers window.scrollBy to smoothly scroll to the target element when clicked. The useRef hooks are used to reference both the button and the target element.
Example: The below example demonstrates the scolling to an HTML element using useEffect and window.scrollBy.
JavaScript
// page.js this is the entry point of application
"use client";
import { useEffect, useRef } from 'react';
const App = () => {
const targetRef = useRef(null);
const buttonRef = useRef(null);
useEffect(() => {
const handleScroll = () => {
if (buttonRef.current) {
buttonRef.current.addEventListener('click', () => {
window.scrollBy({
top: targetRef.current.getBoundingClientRect().top - window.pageYOffset,
left: 0,
behavior: 'smooth',
});
});
}
};
handleScroll();
return () => {
if (buttonRef.current) {
buttonRef.current.removeEventListener('click', handleScroll);
}
};
}, []);
return (
<div style={{ padding: '20px' }}>
<h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
<h3>Approach 2: Using useEffect and window.scrollBy</h3>
<button ref={buttonRef}
style={{ marginBottom: '20px', padding: '10px' }}>
Scroll to GeeksforGeeks Courses
</button>
<div style={{ height: '1000px' }}>
Scroll Down to see the
GeeksforGeeks Courses section
</div>
<div ref={targetRef}
style={{ height: '200px',
background: 'lightblue' }}>
<h2>GeeksforGeeks Courses</h2>
<ul>
<li>Data Structures and Algorithms</li>
<li>Full Stack Development</li>
<li>Machine Learning</li>
<li>Web Development</li>
<li>System Design</li>
</ul>
</div>
</div>
);
};
export default App;
Start your application using the following command.
npm run dev
Output:
Similar Reads
How to Scroll to an Element on click in Angular ?
In this article, we will see how to scroll to an element on click in Angular. Here, we will create a component that enables scrolling to specific targets when a button is pressed within the document from one target to another.Steps for Installing & Configuring the Angular ApplicationStep 1: Crea
4 min read
How to Select the Next Element in CSS ?
Combinators: When classes are combined, they become more specific. This allows you to target classes further down in your template without affecting other elements. Selectors can be combined into a combinator: Combinator of Descendent, Child, Sibling, and General Sibling. The Descendent Combinator i
3 min read
How to Scroll an Element into View in Selenium?
A high-level programming language that helps users in building web applications is called Java. It is not only used for creating web applications but it can also be used for automating web applications through various automation tools. Selenium is one such tool, which gives users the capability to a
4 min read
How to Add Scroll Bar in HTML?
In HTML and CSS, scrollbars can allow users to navigate through the overflowed content within the specified area. They can appear when the content overflows the visible area of the element, such as the <div>, allowing users to scroll horizontally or vertically. we are going to add the scroll b
7 min read
How to Scroll to an Element Inside a Div using JavaScript?
To scroll to an element within a div using JavaScript, set the parent div's scrollTop`to the target element's offsetTop. This method allows smooth navigation within a scrollable container. Below are the methods to scroll to an element inside a Div using JavaScript:Table of Content Using scrollIntoVi
3 min read
How to Create a Scroll To Top Button in React JS ?
You will see there are lots of websites, that are using a useful feature like if you're scrolling the webpage, and now you are at the bottom of that page then you can use this button to scroll up automatically like skip to the content. The following example covers create a Scroll To Top button in Re
3 min read
How To Add Styling To An Active Link In NextJS?
Styling active links is important for enhancing user navigation by providing visual feedback on the current page or section. In Next.js, you can achieve this by using the Link component from next/link and applying styles conditionally based on the active route. In this article, we will learn about h
3 min read
How To Add Navbar To All Pages In NextJS ?
A navbar is a common UI element used to navigate between different sections or pages of a website. Adding a navbar to all pages ensures consistent navigation across the site. This article will explore how we can add a navbar to all pages In NextJS. Output Preview: Prerequisites:NextJSReactJSReact Ho
3 min read
How to scroll to top on every Route click in Angular5 ?
We can use Router and NavigationEnd from '@angular/router' and hence we can scroll to the top of the webpage for every route.Approach:First, we need to import the Router and NavigationEnd from '@angular/router' in both app.module.ts file and app.component.ts.Then we need to create an instance of tho
2 min read
How to run a code on scroll event in jQuery?
In this article, we will discuss how to run the code when users scroll the content using jQuery. To run the code on scrolling the content, the scroll() method is used. The scroll() method is used to run the code when the user scrolls in the specified element.Syntax:$(selector).scroll(function)Parame
2 min read