How to implement a scroll-to-top button in Next.js



Image not found!!

Implementing a scroll-to-top button in a Next.js application involves creating a button that, when clicked, scrolls the page to the top. You can achieve this by using JavaScript and CSS. Here's a simple example of how you can implement a scroll-to-top button in a Next.js project:

  1. Create a new component for the scroll-to-top button:

    In your components directory, create a new file called ScrollToTopButton.js:

    jsx
    import { useState, useEffect } from 'react'; import styles from './ScrollToTopButton.module.css'; // Create a CSS module for styling const ScrollToTopButton = () => { const [isVisible, setIsVisible] = useState(false); useEffect(() => { // Add a scroll event listener to check whether the button should be visible const handleScroll = () => { const scrollTop = window.scrollY; setIsVisible(scrollTop > 100); // Adjust this value based on when you want the button to appear }; // Attach the event listener when the component mounts window.addEventListener('scroll', handleScroll); // Clean up the event listener when the component unmounts return () => { window.removeEventListener('scroll', handleScroll); }; }, []); const scrollToTop = () => { window.scrollTo({ top: 0, behavior: 'smooth', }); }; return ( <button className={`${styles.scrollToTopButton} ${isVisible ? styles.visible : ''}`} onClick={scrollToTop} > Scroll to Top </button> ); }; export default ScrollToTopButton;
  2. Create a CSS module for styling:

    In the same directory as your ScrollToTopButton.js file, create a new file called ScrollToTopButton.module.css:

    css
    .scrollToTopButton { position: fixed; bottom: 20px; right: 20px; background-color: #0070f3; color: #fff; border: none; padding: 10px 15px; cursor: pointer; display: none; transition: opacity 0.3s; } .scrollToTopButton.visible { display: block; }
  3. Use the ScrollToTopButton component in your pages:

    In the pages where you want to include the scroll-to-top button, import and use the ScrollToTopButton component:

    jsx
    import ScrollToTopButton from '../components/ScrollToTopButton'; const YourPage = () => { // Your page content here return ( <div> {/* Your page content */} {/* Scroll-to-top button */} <ScrollToTopButton /> </div> ); }; export default YourPage;
  4. Style the button further (optional):

    Feel free to customize the button's appearance and position by modifying the CSS in the ScrollToTopButton.module.css file.

This implementation should provide a basic scroll-to-top button for your Next.js application. Adjust the styles and behavior based on your specific requirements.