Unusual Behavior of Next.js Layouts

I am puzzled by the unexpected behavior I'm experiencing. When I refresh the page, my navbar momentarily appears and then quickly fades away.

Here is the directory structure of my app:

.
├── actions.tsx
├── api
│   └── test
│       └── route.ts
├── globals.css
├── layout.tsx
└── page.tsx

In layout.tsx:

import "./globals.css";
import { Inter } from "next/font/google";
import Link from "next/link";

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
  title: "Blachere CRM",
  description: "Blachere CRM by Jonathan Lauxen Romano"
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  type NavItem = {
    title: string;
    path: string;
  };

  const navigation: NavItem[] = [
    {
      title: "Home",
      path: "/"
    },
    {
      title: "Contacts",
      path: "/contacts"
    },
    {
      title: "Proposals",
      path: "/newProposal"
    }
  ];

  return (
    <html lang="en">
      <nav className="bg-blue-500 text-white h-12 flex items-center justify-center gap-12">
        {navigation.map((navItem) => (
          <Link key={navItem.title} href={navItem.path}>
            <div>{navItem.title}</div>
          </Link>
        ))}
      </nav>

      <body className={inter.className}>{children}</body>
    </html>
  );
}

And in page.tsx:

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <text>test</text>
    </main>
  )
}

Upon encountering the blinking issue, I received the following errors:

Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.

Error: Hydration failed because the initial UI does not match what was rendered on the server.
Warning: Expected server HTML to contain a matching <nav> in <html>.
See more info here: https://nextjs.org/docs/messages/react-hydration-error

Interestingly, when I pasted the same code onto another page (contacts), it worked perfectly:

.
├── actions.tsx
├── api
│   └── teste
│       └── route.ts
├── contacts
│   ├── layout.tsx
│   └── page.tsx
├── globals.css
├── layout.tsx
└── page.tsx

Can anyone provide insight into what might be causing this issue? How can I rectify it?

Answer №1

A solution is to correct the HTML Code.

Within layout.tsx:

<html lang="en">
  <body className={inter.className}>
    <nav className="bg-blue-500 text-white h-12 flex items-center justify-center gap-12">
      {navigation.map((navItem) => (
        <Link key={navItem.title} href={navItem.path}>
          <div>{navItem.title}</div>
        </Link>
      ))}
    </nav>
    {children}
  </body>
</html>

The issue arises from missing code within the 'body' section. This leads to errors like the one encountered.

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

Challenges with directing angular directives

Setting up my first angular project and struggling with routing. Initially see the template set by preferencesDirective on page load, works well. Clicking "Change Template" button doesn't switch to another template. Even though debugger shows 404 er ...

Ajax success handler failing to process JSON response despite receiving status code 200 or 304

My AJAX call is returning a JSON object successfully in the browser. However, instead of firing the success function, the error block is triggered with a message simply stating "error," which doesn't provide much information. The status returned is ei ...

Does every controller page need to verify the Login Function?

In my PHP pages, I have implemented the MVC Pattern by creating a controller page for each view page to interact with the Model page. However, I have only checked user login at the top of every view page and not in the controller page. This leaves a potent ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

The Javascript code is functioning properly in Chrome, however, it is experiencing compatibility issues in other

Recently, I put together a simple web page using React and Express. One of the modules features a basic form with text input fields, an email input field, and a submit button that is supposed to send an email containing data from the input fields to me. To ...

Updating backgroundPosition for dual background images within an HTML element using Javascript

Issue at Hand: I am currently facing a challenge with two background images positioned on the body tag; one floating left and the other right. The image on the left has a padding of 50px on the left side, while the image on the right has a padding of 50px ...

Send information to the webpage through both GET and POST methods

Can data be submitted to the same page using both the GET and POST methods? Certain sensitive information needs to be sent via POST, while other data such as page_number and search_phrase should be submitted with GET. I attempted creating two forms, one ...

How can Protractor find elements using non-HTML custom attributes?

When running e2e tests on my Angular project using Selenium WebDriver and Protractor, I encountered an issue with locating elements that have custom attributes. For example, I have an element like: <div my-directive my-unique-id="abc123"></div> ...

Having trouble retrieving the accurate count of buttons with a particular class identifier

I have a task where I need to count the number of buttons within a dynamically created div using JavaScript. The buttons are added from a separate JS file and when I view the code in the browser's inspection tool, everything appears to be correct. How ...

Use jQuery to apply a class to the second column within a table

<table> <tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr> <tr><td>aaa</td><td> ...

Encountering the message "Cannot access undefined properties" when attempting to add a new comment

An error message pop-ups when trying to add a comment Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'fullName') Source components\Comment\index.tsx (53:50) @ fullName 51 | <div className={styles. ...

The error message [ERR_HTTP_HEADERS_SENT] is indicating that headers cannot be modified after they have already been sent to the client in a node.js and express

Attempting to retrieve data by Id from records stored in a MSSQL database. For example, trying to make a GET request in Postman like this: localhost:3200/api/v1/players. Encountering an error message: node:_http_outgoing:576 throw new ERR_HTTP_HEADERS_ ...

Leveraging Object.assign for updating fields in Firebase documents

Currently, I am working on a website that allows users to create new projects by filling out a form with all the necessary project information. Within this form, there is a file input field where users can upload images and documents. I have successfully i ...

Retrieve facet queries in JSON format from Solr using JavaScript

Utilizing Solr facets to categorize queried documents by both their category and published date has proven successful. With a query that outputs the desired results in JSON format, the outcome resembles: "facet_counts":{ "facet_queries":{ "pub ...

Adding the height of one element to another element's style value

Having a slight issue with my script. I am trying to retrieve the height of an element and use this value as the top position in CSS for another element. Here is my code snippet: var imageHeight = $('.photo_panel img').height(); $('.close_ ...

Update an existing item or add a new one if it is not already present

I am attempting to create a functionality similar to canva.com, where users can select images from the sidebar and drop them anywhere in the "div", allowing multiple images with individual positions. However, when I use setState(prevState=>{return [...p ...

Is there a way to capture a word from a webpage with just a double click as an input?

I am interested in creating a web application that can take input from the user by double-clicking on a word within the webpage. I have seen this feature utilized in the E2B dictionary Google Chrome extension and would like to implement something similar. ...

Using ng-bind-html within a ng-repeat loop

Currently, I am working on developing a custom autosuggest feature where a web service is queried with a search term to retrieve a list of suggestions that are then displayed. My main obstacle lies in trying to highlight the matching term within the sugges ...

I am looking to integrate a function into an ejs page using a node.js app and express, but I need to ensure that it does not execute

I am currently developing an application in node.js, utilizing mongoose and express. My goal is to pass an asynchronous function that triggers the opening of a browser window using puppeteer to an ejs page, and execute that function only upon clicking a bu ...

Creating an image from the contents of a div is necessary in order to visually

I am looking to develop a software that can: receive text input from the user and place it in a specific div allow users to adjust font, color, and size based on their preferences enable image uploads as background save all customizations and send them v ...