Creating a Scroll Button in Nextjs

힘센캥거루
2025년 1월 13일
23
nextjs

As the length of the posts increased, the issue arose of needing to scroll a lot to navigate to other posts.

Initially, I considered fixing the navbar at the top, but considering that most users now access via mobile, maximizing screen space seemed important.

So, I simply created a button to move to the top.

"use client";

import { ChevronDoubleUpIcon } from "@heroicons/react/20/solid";

export default function MoveToTopBtn() {
  function scrollToTop() {
    window.scrollTo({
      top: 0,
      behavior: "smooth", // Smooth scroll effect
    });
  }
  return (
    <div className="fixed right-6 bottom-6">
      <div
        className="bg-opacity-45 bg-white rounded-full border p-2"
        onClick={scrollToTop}
      >
        <ChevronDoubleUpIcon className="text-gray-500 size-5 font-black stroke-1 stroke-gray-500" />
      </div>
    </div>
  );
}

The implementation is very simple.

Using window.scrollTo to move to the top, smoothly.

And set it to be fixed at the bottom right of the screen through className.

Creating a Scroll Button in Nextjs-1

It smoothly moves to the top when clicked.

댓글을 불러오는 중...