darkroomengineering / lenis

How smooth scroll should be
https://lenis.darkroom.engineering
MIT License
8.52k stars 369 forks source link

Scroll Position Not Resetting on Route Change in Next.js 14.1.2 #360

Closed rubenvangrins closed 3 months ago

rubenvangrins commented 3 months ago

Description

My horizontal website built with Next.js 14.1.2 does not reset the scroll position when changing routes. I want the scroll position to reset on route changes but also to maintain the scroll position when the user clicks the browser's back button.

Components Involved

  1. Scroll Component:

    'use client';
    
    import { useDevice } from '@gewest13/shared/client';
    // @ts-expect-error
    import { ReactLenis } from 'lenis/react';
    
    import { mqTablet } from '@/utils/math';
    
    export default function Scroll({ children }: { children: React.ReactNode }) {
      const vertical = useDevice({ tabletMq: mqTablet });
    
      return (
        <ReactLenis root options={{ orientation: vertical.isTablet ? 'vertical' : 'horizontal', lerp: vertical.isTablet ? 1 : 0.1 }}>
          {children}
        </ReactLenis>
      );
    }
  2. Template Component:

    import Scroll from '@/components/Scroll/Scroll';
    
    export default function Template({ children }: { children: React.ReactNode }) {
      return (
        <Scroll>
          {children}
        </Scroll>
      );
    }
  3. RootLayout Component:

    import Link from 'next/link';
    
    export default function RootLayout({ children }: { children: React.ReactNode }) {
      return (
        <html lang="en">
          <body>
            <ul>
              <li><Link href="/">Home</Link></li>
              <li><Link href="/about">About</Link></li>
            </ul>
    
            {children}
          </body>
        </html>
      );
    }
  4. Page Component:

    export default function Page() {
      return (
        <main style={{ display: 'flex', width: 'fit-content' }}>
          <div style={{ width: '100vw', height: '100vw', backgroundColor: 'red' }} />
          <div style={{ width: '100vw', height: '100vw', backgroundColor: 'blue' }} />
        </main>
      );
    }

Issue Details

Steps to Reproduce

  1. Create a new Next.js project and add the provided components.
  2. Navigate between routes (e.g., from Home to About).
  3. Observe that the scroll position does not reset on route change unless the style is removed from Page.tsx.

Expected Behavior

The scroll position should reset to the left when navigating to a new route but should maintain the position when the user navigates back using the browser's back button.

clementroche commented 3 months ago

Since Lenis doesn't affect your scroll position on page change, i guess that's a Next.js issue. Please be sure this behaviour occurs only when Lenis is applied.

rubenvangrins commented 3 months ago

I've updated my lenis package and not it works..