Smooth Scrolling with lenis: A Full Guide
Aug 25, 2024
Scrolling is an essential part of web navigation. Smooth Scrolling in particular can enhance user experience, making the reactions feel fluid and seamless. Enter Lenis a Lightweight JavaScript library for smooth Scrolling (around 4kb check official website). Weather you are creating a blog website or a complex web app, Lenis can help you achieve smooth scrolling with minimal effort.
What is Lenis:
It's an easy-to-use modern library for implementing smooth scrolling in web pages, it abstracts the complexities of achieving smooth scrolling effects by providing a clean API to work with.
Check The Official Website
Key Features:
- Lightweight: Lenis is a lightweight library which is crucial for performance and speed.
- Easy to use: the API is super easy to use as we'll see in the coming sections.
- Performance: It was developed with performance mind, providing smooth effects without affecting the website speed.
- Customization: Customize scrolling effects based on your needs.
Why use Lenis js:
-
Enhanced User Experience
Smooth scrolling create a polished professional experience for websites. reduces bumpy transitions and improves the user experience. -
Accessibility
Lenis Ensures not only appealing smooth scrolling but also accessibility. It handles different input methods gracefully. Making all users have a consistent experience. -
Ease of use
The API is super easy to use and you do not need to worry about the scrolling mechanisms. -
Customization
It allows to tune the scroll behavior based on your needs. (ex: smoothness, easing,speed, etc.)
Lenis Example With React
Let's create a smooth scrolling example using Lenis and React.
Step 1: Install Lenis
Using NPM:
Using Yarn:
Step 2: Basic Setup
Create a Custom Hook to facilitate the process
Step 3: Use The Hook
Now let's use the hook in the wanted component in order to create smooth scrolling.
In the example I'll put it in the App component. to ensure smooth scrolling in the whole app.
This setup enables smooth scrolling with minimal configuration.
Advanced Usage
Custom Scroll Behavior
If you want to change some of the default behavior, you can do it with ease. In this example I will change the scroll direction to horizontal.
Check the official Documentation for more details.
Controlling scroll with JavaScript
Here a simple example to control the scroll with JavaScript. using Lenis methods
This feature is particularly useful for creating scroll-based navigation or dynamic effects that respond to user interactions.
Conclusion
Lenis is a powerful solution for smooth scrolling. It's a lightweight library that provides a smooth and intuitive experience for websites. It's also easy to use and customizable.
Happy Hacking!