The current issue with the Next.js 13 beta application is that the nested layout directory does not scroll to the top when the route is

Check out the live demo here. Ensure to scroll down and click on a link in the header.

In my project, I have two files named layout.tsx: one in the src directory and another in the (public) directory with a sticky <Header /> component. The expected behavior is for the page to scroll to the top when a route changes using a <Link>.

However, what actually happens is that the page scrolls to the top except for the height of the Header. Even after adding scrollRestoration: true in next.config.js, the issue persists. It's also present in the latest canary release.

Moreover, I keep encountering a Hydration error when refreshing the page multiple times. I'm unsure if these issues are connected.

Before submitting an issue on GitHub, I would like assistance in determining if my layout structure is incorrect or if I am misusing the new layout feature.

Your help in identifying the root cause of these problems would be greatly appreciated, as it's been quite frustrating for me.

├──(public)
│   ├── page.tsx
│   └── layout.tsx
└── layout.tsx (root layout)
// src/layout.tsx

import "assets/styles/globals.css";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <head />
      <body>{children}</body>
    </html>
  );
}
// src/(public)/header.tsx

import Link from "next/link";

const Header = () => {
  return (
    <div className="bg-gray-200 h-12 sticky top-0 z-50">
      <div className="flex flex-row mx-auto max-w-7xl h-full space-x-4 items-center ">
        <Link href="/">Home</Link>
        <Link href="/about">About</Link>
        <Link href="/contact">Contact</Link>
      </div>
    </div>
  );
};

export default Header;
// src/(public)/layout.tsx

import Header from "./header";

export default function PublicLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <>
      <Header />
      <main className="py-16">{children}</main>
    </>
  );
}

// I've tried <main className="py-16"><Header />{children}</main> but the issue persisted

Answer №1

I have verified that the latest version of "next" has resolved this problem.

Make sure to upgrade the next package from 13.1.1 to 13.4.3.

"next": "13.4.3",

Answer №2

Make sure to implement this code snippet in your layout page:

 useEffect(() => {
    window.scrollTo({
      top:0,
      left:0,
      behavior: 'smooth',
    })
  }, [])

Answer №3

I have a helpful solution to address this issue. We can include the following code snippet in our project:

useEffect(() => { // 👇️ scroll to top on page load
  window.scrollTo({top: 0, left: 0, behavior: 'smooth'});
}, []);

Place this code in the layout.tsx file so that it runs every time the route is re-rendered.

Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are there any benefits to utilizing the Mantra.js architectural framework?

I have found that integrating Meteor.js into a Mantra.js architecture works seamlessly. However, I am questioning the advantages of using it since it seems to slow down the running of my requests. For example, when making a dummy request in GraphQL (such ...

Issue with dispatching actions in React using TypeScript and hooks

Can you please point out what I'm doing wrong here: I am encountering the following error Type '{ wishList: any; addBookToWishList: (book: any) => void; }' is not assignable to type '{ wishList: never[]; }'. Object literal may onl ...

What is the method for retrieving the request/response on an application router page?

If you're working in the pages router, one approach is to use a getStaticProps function to pass props into your component. This function receives request and response objects as arguments, allowing you to access any relevant information from them. In ...

What is the process for activating the currently active tab or link within the MDBNav component of MDBreact?

Here is the code snippet I am working with: import React from "react"; import { BrowserRouter } from 'react-router-dom'; import { MDBNav, MDBNavItem, MDBNavLink } from "mdbreact"; const CustomTabs = props => { return ( <BrowserRouter& ...

Tips for resolving the trigger problem with onChange in the PinInput Component of chakra-ui

The PinInput Component's onChange event is not functioning properly with the value in Chakra-UI. This issue causes the focus to automatically shift to the next input even when the value hasn't changed. For instance, when attempting to set the st ...

Using Tailwind CSS to set the margin of an element at certain breakpoints is not functioning as expected

I attempted to customize the margin of a div element at specific screen sizes by using a {screen}: prefix, but it did not have the desired effect. Here is what I tried: <div className={'flex justify-center'}> <div className={'w-fu ...

Is there a method to verify the status of an onSnapshot listener?

There have been instances when I've observed that the link between the browser tab and Firestore gets disconnected for unknown reasons, leading to unsuccessful re-connection. Is there a reliable method to determine if your onSnapshot is still activel ...

Loading data dynamically in a table by utilizing the react WayPoint library

I'm currently utilizing a combination of material UI table and react-table. When the number of rows in the table exceeds around 200, the performance dips. To address this issue, I am looking to display a fixed number of rows (let's say 20 rows) i ...

Creating a Material UI Gmail Tasks Toolbar with a similar design

Hello, I'm interested in learning how to achieve a similar style to the new Gmail Tasks app. The new Gmail user interface is inspired by Material Design principles. As I am working on developing a Gmail Add-on using React and InboxSDK, I want to repl ...

Can you help me find the missing loader reference in my webpack configuration?

Encountering a particular issue with my webpack configuration while working on a new project. For some reason, my react code is not being bundled correctly and I keep getting the following error message: ERROR in ./index.jsx 47:6 Module parse failed: Unex ...

The utilization of media within the meta in Next.js is not allowed

Recently, I came across an interesting article about PWAs on web.dev. The article discusses color schemes and at one point, they talk about it in detail, I'm currently working with Next.js and decided to try implementing the following code snippet: & ...

Navigating the grid layout in Material UI can be tricky to

I'm struggling to grasp the concept of the grid system in material UI. Within my grid container, I have two grid items that I want to be centered and occupy the entire width. The button element appears centered, but the typography element does not. A ...

Looking for assistance in integrating custom data into session.user object with next-auth

I am having trouble adding custom data to the session.user object and it is not working as expected. What's strange is that when I send this: const user = { id: '1', name: "J Smith", email: "<a href="/cdn-cgi/l/email-protection" class="__ ...

Issue with nextJS/Firebase database while experimenting with enabling web frameworks

I encountered an issue with a nextJS app I built on Firebase, following the steps and running the commands mentioned below: % npx create-next-app@latest % cd myapp % firebase experiments:enable webframeworks % npm install -g firebase-tools % firebase ...

When the SVG icon is clicked, it will redirect to a different page

I'm trying to figure out how to add a href attribute to an SVG icon in order to redirect to another page when the icon is clicked. I've saved the SVG icon as a React Component, but I'm unsure of what steps to take next. import React from &ap ...

Exploring dynamic page creation with Nextjs, utilizing Contentful for data management and implementing

My goal is to generate dynamic pages by clicking on tags within an article or elsewhere on my website. I am utilizing Next.js, SSG, and fetching articles with specific tags from Contentful using GraphQL queries: export async function getArticles() { con ...

What causes React component state initialization to return a `never` type when set to null?

Initializing a component's state to null outside of the constructor results in the state having the type never in the render function. However, when the state is initialized within the constructor, the correct type is maintained. Despite many StackO ...

The following error occurred: Next Auth TypeError: URL is not valid

Every time I run my Nextjs project, I keep encountering an issue related to Next Auth. Despite using version 4.3.1, I am unsure about how to resolve it. Any assistance with next-auth would be greatly appreciated. Although I attempted to update my next-aut ...

What is the best way to securely transfer API keys to a React frontend for use in a React component?

I'm currently working with @react-google-maps/api to develop a map component in React. To load the component, we have to provide an API key for useJsApiLoader. How can I securely manage the API key so it's not exposed on the frontend? (Using an E ...

Customize the disabled styles for InputBase in Material UI

Struggling to figure out how to override the given rule on an InputBase: .MuiInputBase-root.Mui-disabled { color: rgba(0, 0, 0, 0.38); } The desired rule is: color: "rgba(0, 0, 0, 0.75)" Tried using classname and classes without success. Any suggest ...