💨
【GSAP】GSAP Practice【#21 GSAP Nextjs Lenis Setup】
【#21 GSAP Nextjs Lenis Setup】
YouTube: https://youtu.be/2GU6rgkxIfY
今回はNextjsでlenisを使用する方法について解説します。
通常の「lenis」のみで実装する方法と
「lenis/react」を使用する方法がありますが
まずは、通常の「lenis」で
実装する方法について解説していきます。
最初にスクロールできる要素を作成します。
app/page.tsx
export default function Home() {
return (
<main className="w-screen h-screen">
<div className="size-full flex items-center justify-center bg-slate-300">
<h2 className="text-3xl font-bold">Section1</h2>
</div>
<div className="size-full flex items-center justify-center bg-rose-300">
<h2 className="text-3xl font-bold">Section2</h2>
</div>
<div className="size-full flex items-center justify-center bg-sky-300">
<h2 className="text-3xl font-bold">Section3</h2>
</div>
</main>
)
}
次にlenisのプロバイダーを作成します。
providers/lenis-provider.tsx
'use client'
import { useEffect } from 'react'
import Lenis from 'lenis'
interface LenisProviderProps {
children: React.ReactNode
}
export const LenisProvider = ({ children }: LenisProviderProps) => {
useEffect(() => {
const lenis = new Lenis()
function raf(time: number) {
lenis.raf(time)
requestAnimationFrame(raf)
}
requestAnimationFrame(raf)
}, [])
return <>{children}</>
}
最後に上記プロバイダーを「layout.tsx」に設定します。
app/page.tsx
import type { Metadata } from 'next'
import { Geist, Geist_Mono } from 'next/font/google'
import { LenisProvider } from '@/providers/lenis-provider'
import './globals.css'
const geistSans = Geist({
variable: '--font-geist-sans',
subsets: ['latin'],
})
const geistMono = Geist_Mono({
variable: '--font-geist-mono',
subsets: ['latin'],
})
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<LenisProvider>{children}</LenisProvider>
</body>
</html>
)
}
Discussion