Buttery-Smooth Scrolling on your website in 2 minutes!

Buttery-Smooth Scrolling on your website in 2 minutes!

Smooth Scrolling in React app using Lenis.

Smooth scrolling enhances the user experience by providing fluid transitions between sections of your website. While it may not be to everyone's taste, it does add a much more polished and natural feel to it.

Want smooth scrolling on your website like this? Do it in a few easy steps with Lenis!

Lenis by Studio Freight is a lightweight open-source library that provides a robust and customizable smooth-scrolling experience across devices. In this tutorial, we are going to use their react-lenis package built specifically for the React framework. With react-lenis, we do not have to worry about prop drilling for the Lenis instance.

Now, let's jump into the tutorial! ⏬

Step 1: Set up the React project.

Create the React app. I'll be using Vite for it.

npm create vite@latest my-project -- --template react
cd my-project

Install the dependencies.

npm install

Install the react-lenis package.

npm i @studio-freight/react-lenis

Great! Now we are good to go. 🔥

npm run dev

Step 2: Create a wrapper component.

Now, let's create a wrapper component to wrap our App with the React-Lenis component.

import { ReactLenis } from "@studio-freight/react-lenis";

function SmoothScrolling({ children }: { children: React.ReactNode }) {
  // lenis options for configuration
  const lenisOptions = {
    lerp: 0.1,
    duration: 1.5,
    smoothTouch: false, //smooth scroll for touch devices
    smooth: true,
  };

  return (
    <ReactLenis root options={lenisOptions}>
      {children}
    </ReactLenis>
  );
}
export default SmoothScrolling;

The <ReactLenis> component creates a Lenis instance and sends it to our application (children) via context.

Step 3: Wrap the application with the wrapper component.

Finally, we are going to wrap our main application with the wrapper we just created!

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import SmoothScrolling from "./utils/smoothScrolling.tsx";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    // wrappper here
    <SmoothScrolling>
      <App />
    </SmoothScrolling>
  </React.StrictMode>
);

Yay!! 🥳 There you have it! Enjoy a buttery-smooth scrolling experience in your application!


Thanks for stopping by! Hope the article helped!