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:
useState
anduseEffect
are imported from the React library. They are React hooks used for managing state and performing side effects in functional components.Link
is imported from thenext/link
module. It is used in Next.js for client-side navigation.
-
Function Definition:
ScrollLink
is a functional component that takes two props:id
andchildren
.id
is the ID of the element to which the link should scroll.children
represents 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
Link
component from Next.js wrapped around adiv
. - The
href
attribute of theLink
component is set to#${id}
, which means clicking the link will navigate to the element with the specifiedid
within the same page. passHref
is used to pass thehref
prop to the underlyinga
tag.- The
onClick
event of thediv
is set to thehandleClick
function. - The content of the link (
children
) is rendered inside thediv
.
- The component returns a
-
Export Statement:
- The
ScrollLink
component 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
id
property ascontacts
and the childtext
asContacts
in 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