How to implement a smooth scroll navigation in Next.js



Image not found!!

To implement smooth scroll navigation in a Next.js application, you can use a combination of React, Next.js, and a smooth scrolling library like react-scroll. Here's a step-by-step guide:

  1. Install the required packages:

    bash
    npm install react-scroll
  2. Create a new component for smooth scrolling. For example, you can create a file named SmoothScroll.js:

    jsx
    // SmoothScroll.js import React from 'react'; import { Link as ScrollLink } from 'react-scroll'; const SmoothScroll = ({ to, children }) => { return ( <ScrollLink activeClass="active" to={to} spy={true} smooth={true} offset={-70} // Adjust this offset based on your layout (e.g., the height of your navbar) duration={500} > {children} </ScrollLink> ); }; export default SmoothScroll;
  3. Use the SmoothScroll component in your navigation bar or wherever you want smooth scrolling. For example, in your Navbar.js:

    jsx
    // Navbar.js import React from 'react'; import SmoothScroll from './SmoothScroll'; const Navbar = () => { return ( <nav> <ul> <li> <SmoothScroll to="section1">Section 1</SmoothScroll> </li> <li> <SmoothScroll to="section2">Section 2</SmoothScroll> </li> {/* Add more items as needed */} </ul> </nav> ); }; export default Navbar;
  4. Use the Navbar component in your main layout or page component. For example, in your pages/index.js:

    jsx
    // pages/index.js import React from 'react'; import Navbar from '../components/Navbar'; const Home = () => { return ( <div> <Navbar /> <section id="section1"> <h1>Section 1</h1> {/* Content of Section 1 */} </section> <section id="section2"> <h1>Section 2</h1> {/* Content of Section 2 */} </section> {/* Add more sections as needed */} </div> ); }; export default Home;
  5. Optionally, you may need to add styles for the active link in your CSS. For example, in your styles/globals.css:

    css
    /* styles/globals.css */ .active { color: #00f; /* Change the color as needed */ }
  6. Run your Next.js application:

    bash
    npm run dev

Now, when you click on the navigation links, the page should smoothly scroll to the corresponding sections. Adjust the offset value in the SmoothScroll component to match your layout and consider adding more styling based on your design requirements.