Scroll to Top Button: A React Component You'll Use in Every Project

As a front-end developer, I'm always on the lookout for components that can enhance user experience across multiple projects. The scroll-to-top button is one such component that I find myself implementing time and time again. Instead of reinventing the wheel for each project, I decided to create a reusable, customizable version and share it right here on my website. Not only does this save me time, but it also allows fellow developers to benefit from a tried-and-tested solution. So, whether you're working on a personal blog or a complex web application, this component is bound to come in handy!

Today, I'm excited to share with you a React component that creates a stylish and functional scroll-to-top button, inspired by the sleek design of Google Chrome's interface. The best part? It's built with Framer Motion, adding a touch of elegance with smooth animations. Trust me, once you see how this button gracefully appears and playfully jumps on hover, you'll want to add it to all your projects!

Here is the code:

'use client'
import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { ChevronUpCircleIcon } from 'lucide-react'

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

const toggleVisibility = () => {
setIsVisible(window.scrollY > 500)
}

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

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

const jumpAnimation = {
y: [0, -10, 0, -10, 0],
transition: {
y: {
duration: 0.7,
ease: 'easeOut',
repeat: 1,
},
},
}

return (

<motion.div
  initial={{ opacity: 0, scale: 0.8 }}
  animate={{ opacity: isVisible ? 1 : 0, scale: isVisible ? 1 : 0.8 }}
  transition={{ duration: 0.4 }}
  className="fixed bottom-16 right-5 z-50"
>
  {isVisible && (
    <motion.button
      whileHover={jumpAnimation}
      onClick={scrollToTop}
      aria-label="Back to top"
    >
      <ChevronUpCircleIcon
        size={40}
        absoluteStrokeWidth={true}
        strokeWidth={1.5}
      />
    </motion.button>
  )}
</motion.div>
) } export default BackToTopButton

Now, let's break down the key features and functionality of this component:

  1. Client-Side Rendering: The 'use client' directive ensures this component works correctly in Next.js applications by enabling client-side features. This is crucial for handling scroll events and smooth animations.

  2. State Management: We use the useState hook to manage the button's visibility based on the scroll position. It's a simple yet effective way to control when the button appears.

  3. Scroll Event Handling: An event listener is added to the window to toggle the button's visibility when the user scrolls more than 500 pixels down the page. This threshold is easily adjustable to suit your specific needs.

  4. Smooth Scrolling: The scrollToTop function uses the window.scrollTo method with behavior: 'smooth' for a buttery-smooth scrolling effect. It's these little details that make a big difference in user experience!

  5. Animations: Here's where Framer Motion really shines! We use it to add subtle yet delightful animations:

    • The button fades in and scales up when it appears, drawing just the right amount of attention.
    • A playful "jump" animation is triggered on hover, adding a fun interactive element.

    Isn't it cool how a few lines of animation code can bring so much life to a simple button? That's the magic of Framer Motion!

  6. Accessibility: The button includes an aria-label for better screen reader support. Always remember, great UX is accessible UX!

  7. Customizable Icon: The component uses the ChevronUpCircleIcon from Lucide React, which can be easily customized or replaced. I love how Lucide icons blend seamlessly with modern UI designs.

To use this component in your React project, follow these simple steps:

  1. Install the necessary dependencies:
npm install framer-motion lucide-react
  1. Copy the BackToTopButton component into your project.
  2. Import and use the component in your desired location:
import BackToTopButton from './path/to/BackToTopButton'

function App() {
  return (
    <div>
      {/* Your app content */}
      <BackToTopButton />
    </div>
  )
}

The beauty of this component lies in its simplicity and flexibility. You can easily customize it by adjusting the scroll threshold, modifying the button's position using Tailwind classes, changing the icon, or tweaking the animations to suit your project's needs.

This scroll-to-top button component offers a perfect blend of functionality and aesthetics, designed to enhance the user experience of your React applications. It's a small addition that can make a big impact on how users interact with your long-scrolling pages.

So, go ahead and give it a try in your next project! I'd love to hear how you've customized it or if you've made any cool modifications. Remember, great web design is all about these thoughtful details that make browsing a joy for your users.

Happy coding, and may your websites always be a scroll away from the top!