How to useScroll Event Listener in CSS
The Scroll Event Listener is used to implement the reveal on scroll effect in React using Tailwind CSS. It involves attaching an event listener to the scroll event of the window object or any scrollable element. When the user scrolls, the event listener fires and triggers the associated callback function.
Example: This example implements revel on scoll using scroll event listener to trigger and reveal content with cusotm scroll values.
Javascript
// Filename - App.js import React, { useEffect, useRef, useState } from "react" ; const RevealOnScroll = ({ children }) => { const [isVisible, setIsVisible] = useState( false ); const ref = useRef( null ); useEffect(() => { const onWindScroll = () => { const element = ref.current; if (element) { const { top } = element.getBoundingClientRect(); const isVisible = top < window.innerHeight; setIsVisible(isVisible); } }; window.addEventListener( "scroll" , onWindScroll); return () => { window.removeEventListener( "scroll" , onWindScroll); }; }, []); const classes = `transition-opacity duration-1000 ${isVisible ? "opacity-100" : "opacity-0" }`; return ( <div ref={ref} className={classes}> {children} </div> ); }; const App = () => { return ( <div className= "container mx-auto text-center" > <h1 className= "text-7xl font-bold mb-8 text-green" > w3wiki </h1> <h2 className= "text-4xl " > Reveal on Scroll in React using Tailwind CSS </h2> <RevealOnScroll> <p className= "text-3xl h-[15em] mt-[10em]" > Welcome to the computer science portal! </p> </RevealOnScroll> <RevealOnScroll> <p className= "text-3xl h-[15em] mt-[10em]" > Learn Web Development </p> </RevealOnScroll> <RevealOnScroll> <p className= "text-3xl h-[15em] mt-[10em]" > Learn Android Development </p> </RevealOnScroll> <RevealOnScroll> <p className= "text-3xl h-[15em] mt-[10em]" > Learn Data Stuctures and Algorithms </p> </RevealOnScroll> <RevealOnScroll> <p className= "text-3xl h-[15em] mt-[10em]" > and more... </p> </RevealOnScroll> </div> ); }; export default App; |
Steps to Run the Application: Use this command in the terminal in the project directory.
npm start
Output: This output will be visible on the http://localhost:3000 on the browser window
How to Implement Reveal on Scroll in React using Tailwind CSS ?
In React, the reveal on the scroll is a technique, where elements on a page gradually appear or animate as the user scrolls down.