In this Article
Introduction
In this short tutorial we'll learn how to create links that smoothly scroll to specific sections of a NextJS web page when clicked. At the time of writing I am using Next.js version 14.1.4 but other versions should work as well.
What to do?
Firstly define a reusable React component. I named it ScrollLink in this example.
// components/ScrollLink.jsx
The links in this component will enable the users to scroll smoothly to a specified section of a webpage when clicked.
Code for the component
Code for the ScrollLink component:
// components/ScrollLink.jsx
import { useState, useEffect } from 'react';
import Link from 'next/link';
function ScrollLink({ id, children }) {
const handleClick = (e) => {
e.preventDefault();
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
};
return (
<Link href={`#${id}`} passHref>
<div onClick={handleClick}>{children}</div>
</Link>
);
}
export default ScrollLink;
Code breakdown
Here's a breakdown of what each part of the code does:
-
Import Statements:
useStateanduseEffectare imported from the React library. They are React hooks used for managing state and performing side effects in functional components.Linkis imported from thenext/linkmodule. It is used in Next.js for client-side navigation.
-
Function Definition:
ScrollLinkis a functional component that takes two props:idandchildren.idis the ID of the element to which the link should scroll.childrenrepresents the content of the link.
-
handleClick Function:
- This function is called when the link is clicked.
- It prevents the default behavior of the link (navigating to a new page).
- It retrieves the DOM element with the specified
id. - If the element exists, it scrolls to it smoothly using
scrollIntoView({ behavior: 'smooth' }).
-
Return Statement:
- The component returns a
Linkcomponent from Next.js wrapped around adiv. - The
hrefattribute of theLinkcomponent is set to#${id}, which means clicking the link will navigate to the element with the specifiedidwithin the same page. passHrefis used to pass thehrefprop to the underlyingatag.- The
onClickevent of thedivis set to thehandleClickfunction. - The content of the link (
children) is rendered inside thediv.
- The component returns a
-
Export Statement:
- The
ScrollLinkcomponent is exported as the default export of the module, making it available for use in other parts of the application.
- The
Implementation Example
Make sure the target elements - sections or divs - have an ID attribute set to them properly
Let say we want to navigate to the contacts section:
<section id='contacts'>
...
</section>
- Import the ScrollLink reusable component at the top of your navigation component:
import ScrollLink from './ScrollLink';
- Call the ScrollLink component and set your
idproperty ascontactsand the childtextasContactsin your navigation component:
import ScrollLink from './ScrollLink';
const Navbar = () => {
return (
...
<ul>
<li>
<ScrollLink id="contacts">Contacts</ScrollLink>
</li>
</ul>
...
);
};
export default Navbar;
Implementing the above code correctly will enhancing the user experience of navigating within a single-page application.
References & Additional Resources
Inspiration for this article came from a Stackoverflow post below:
NextJs - Link to scroll to a section in same page
GlenH - Mar 24, 2024gghayoge at gmail.com