To add a “Scroll to Top” button in a Next.js TypeScript project

To add a “Scroll to Top” button in a Next.js TypeScript project, follow these steps:

1. Create the ScrollToTop component

Create a reusable component that:

  • Listens to scroll position
  • Shows a button when scrolled down
  • Scrolls smoothly to top on click

components/ScrollToTop.tsx

'use client';

import { useEffect, useState } from 'react';

const ScrollToTop = () => {
  const [isVisible, setIsVisible] = useState(false);

  // Show button when scrollY > 300
  const toggleVisibility = () => {
    setIsVisible(window.scrollY > 300);
  };

  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  };

  useEffect(() => {
    window.addEventListener('scroll', toggleVisibility);
    return () => window.removeEventListener('scroll', toggleVisibility);
  }, []);

  return (
    <button
      onClick={scrollToTop}
      className={`fixed bottom-6 right-6 p-3 rounded-full bg-blue-600 text-white shadow-lg transition-opacity ${
        isVisible ? 'opacity-100' : 'opacity-0'
      }`}
      aria-label="Scroll to top"
    >
      ↑
    </button>
  );
};

export default ScrollToTop;

2. Use it in your layout or page

Add this component in your layout or specific page so it’s always present.

Example in app/layout.tsx (App Router)

import ScrollToTop from '@/components/ScrollToTop';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <ScrollToTop />
      </body>
    </html>
  );
}

Or in a specific page:

import ScrollToTop from '@/components/ScrollToTop';

const HomePage = () => (
  <>
    {/* Your content */}
    <ScrollToTop />
  </>
);

export default HomePage;

Leave a comment

Your email address will not be published. Required fields are marked *