Adding Animations

Read time: 1 minute
Mitchell Christ
Mitchell Christ
a cute girl with a bored expression, typing on a macbook with the text "anim-fade-to-r" on the front OLED screen, in an office cubicle, 80s retro anime screengrab

.anim-fade and .anim-fade-to-* CSS classes

This starter template comes included with the following CSS classes to add basic fading animations to HTML elements that are triggered onload, when not display: none, or when state changes:

  • anim-fade — Simple fade from opacity 0%
  • anim-fade-to-l — Fade and slide right-to-left ⬅️
  • anim-fade-to-r — Fade and slide left-to-right ➡️
  • anim-fade-to-t — Fade and slide bottom-to-top ⬆️
  • anim-fade-to-b — Fade and slide top-to-bottom ⬇️

The slide distance and animation duration can be overwritten with Tailwind and CSS custom variables: --x and --y.

Usage

  • {/* triggers onload or when display is not hidden */}
    <div class="anim-fade"> ... </div>
    
    {/* Add a `key` to trigger when `state` changes */}
    <div class="anim-fade" key={state}> ... </div>
    
    {/* overriding the Y distance and duration */}
    <details>
    	<summary>Summary</summary>
    	<div class="anim-fade-to-b [--y:2rem] [animation-duration:2s]">
    		...
    	</div>
    </details>

    Animating elements when scrolled into view

    I recommend installing the AOS library to trigger animations when elements are scrolled into the viewport.

  • npm install aos

    Add a new React component to initialize the AOS library to allow for adding data-aos-* attributes to any React/HTML element. Global AOS options will also be configure here.

    src/ui/AOS.tsx
  • 'use client'
    
    import { useEffect } from 'react'
    import 'aos/dist/aos.css'
    
    export default function AOS() {
    	useEffect(() => {
    		import('aos').then((AOS) => {
    			AOS.init({
    				// global settings
    				once: true,
    				duration: 600,
    			})
    		})
    	}, [])
    
    	return null
    }

    Then insert the <AOS/> component inside the Next.js layout file.

    src/app/(frontend)/layout.tsx
  • import AOS from '@/ui/AOS'
    
    export default async function RootLayout({ children }) {
    	return (
    		<html lang="en">
    			<body> ... </body>
    
    			<AOS />
    		</html>
    	)
    }

    Finally, add data-aos-* attributes to your React/HTML elements.

  • <div data-aos="fade"> ... </div>
    
    {/* use `key` to add delays */}
    {items?.map((item, key) => (
    	<div
    		data-aos="fade-right"
    		data-aos-delay={key * 100}
    		key={key}
    	>
    		...
    	</div>
    ))}

    More options are found on the official AOS documentation.

    a cute girl with a bored expression, typing on a macbook with the text "animations" on the front OLED screen, in an office cubicle, 80s retro anime screengrab