😺
Next.js 13 (App router)でLenisを使用
概要
Next.js(App router)にてLenisを導入する備忘録。
- next: 13.5.6
必要なパッケージのインストール
npm i @studio-freight/lenis @studio-freight/tempus
// or
yarn add @studio-freight/lenis @studio-freight/tempus
コンポーネントの作成
src/app/components/Lenis.tsx
'use client'
import React, { useEffect, useLayoutEffect, useRef } from 'react';
import Tempus from '@studio-freight/tempus';
import Lenis from '@studio-freight/lenis';
import { usePathname, useSearchParams } from 'next/navigation';
export default function SmoothScroller() {
const lenis = useRef<Lenis | null>(null);
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
if (lenis.current) lenis.current.scrollTo(0, { immediate: true });
}, [pathname, searchParams, lenis]);
useLayoutEffect(() => {
lenis.current = new Lenis({
smoothWheel: true,
// Customize other instance settings here
});
const resize = setInterval(() => {
lenis.current!.resize();
}, 150);
function onFrame(time: number) {
lenis.current!.raf(time);
}
const unsubscribe = Tempus.add(onFrame);
return () => {
unsubscribe();
clearInterval(resize);
lenis.current!.destroy();
lenis.current = null;
};
}, []);
return null;
}
src/app/layout.tsx
import React from "react";
import SmoothScroller from "@/components/Lenis"; // Adjust the import path as needed
export default function RootLayout({
children,
}: {
children: React.ReactNode,
}) {
return (
<html>
<body>
<SmoothScroller />
{children}
</body>
</html>
);
}
Discussion