Alert: The `className` property did not align and there is an absence of the window within the Next 13 App Router

I've been struggling to fix an error in the Next.js 13 App Router.

Warning: Prop `className` did not match. 
Server: "styled__HeadLink-sc-6589f63-0 fIOFTm" 
Client: "styled__HeadLink-sc-b76127ed-0 jzAIeh"

I've spent a lot of time searching online for solutions to this issue. Errors can be quite challenging to pinpoint and resolve.

  • To address this problem, I followed advice from various online sources.

Here is my .babelrc configuration:

{
  "env": {
    "development": {
      "presets": ["next/babel"],
      "plugins": [["babel-plugin-styled-components", { "ssr": true, "displayName": true, "preprocess": false }]]
    },
    "production": {
      "plugins": [["babel-plugin-styled-components", { "ssr": true, "displayName": true, "preprocess": false }]],
      "presets": ["next/babel"]
    },
    "test": {
      "presets": ["next/babel"]
    }
  },
  "plugins": [["babel-plugin-styled-components", { "ssr": true, "displayName": true, "preprocess": false }]]
}

And here is my next.config.js setup:

reactStrictMode: false,
  compiler: {
    styledComponents: true,
  },

In my code, I used window checks like this:

export const isClient = () => typeof window !== 'undefined';

I also attempted to use next/dynamic as shown below:

export default dynamic(() => Promise.resolve(VeryTroubleBlock), { ssr: false });

The root of the issue seems to lie in the initial rendering of Swiper on specific pages.

const isTablet = useAdaptiveSize(Breakpoints.tablet);
const isMobile = useAdaptiveSize(Breakpoints.mobile);

// Swiper component usage here...

export default dynamic(() => Promise.resolve(VeryTroubleBlock), { ssr: false });

My custom hook implementation looks like this:

import { isClient } from '@/utils/client-check';
import { useState, useLayoutEffect } from 'react';
import { useWindowSize } from 'usehooks-ts';

export function useAdaptiveSize(size: number): boolean {
  // Hook logic here...
}

While my custom hook resolved the issue on one page, it persists on another where Swiper is being utilized.

To eliminate the "Warning: Prop className did not match" error, replacing the custom hook execution with

innerWidth < Breakpoints.tablet
should work. However, this may lead to a server-side console error due to window is not defined.

I welcome any feedback and assistance in resolving this issue.

Have a wonderful day!

Answer №1

Issue: The problem arose when I realized that my global styles were written in CSS, while the rest of the styles were implemented using styled-components.

Solution: In order to tackle this issue effectively, I made the decision to transition completely to utilizing Styled-components for all styling requirements. This ensured a cohesive styling approach and maintained consistency in styling across both server-side and client-side rendering processes. Additionally, I made a specific change by eliminating the use of React.Fragment <></> within the StyleSheetManager during the return styles phase.

'use client';

import React, { useState } from 'react';
import { useServerInsertedHTML } from 'next/navigation';
import { ServerStyleSheet, StyleSheetManager } from 'styled-components';

export default function StyledComponentsRegistry({ children }: { children: React.ReactNode }) {
  // Create stylesheet only once with lazy initial state
  // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
  const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet());

  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement();
    styledComponentsStyleSheet.instance.clearTag();
    return styles;
  });

  if (typeof window !== 'undefined') return <>{children}</>;

  return <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>{children}</StyleSheetManager>;
}

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

Why does this particular check continue to generate an error, despite my prior validation to confirm its undefined status?

After making an AJAX call, I passed a collection of JSON objects. Among the datasets I received, some include the field C while others do not. Whenever I try to execute the following code snippet, it causes the system to crash. I attempted using both und ...

What is the most effective method for dividing a string in TypeScript?

Here is the scenario: receiving a string input that looks like Input text: string = "today lunch 200 #hotelname" Output subject: "today lunch" price: 200 tag: #hotelname My initial solution looks like this: text: string = "today lunch 200 #hotelname" ...

Prevent tooltip text from appearing when a button is disabled in an angular application

As a beginner in UI development, I have a requirement for my Angular application. I need to enable and disable a button based on certain conditions. The tricky part is that I want to display a tooltip only when the button is enabled. I have managed to chan ...

What is the best way to eliminate the external pause button?

My website contains the following HTML snippet: <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="a ...

Error: Trying to access property '2' of a null value

I’ve been working on a project using Next.js with TypeScript, focusing on encryption and decryption. Specifically, I’m utilizing the 'crypto' module of Node.js (@types/nodejs). However, I encountered an error while attempting to employ the &a ...

Utilizing a Nodemailer template with a JSX/React component: A step-by-step guide

Currently utilizing Next.js with Nodemailer, my goal is to incorporate React / JSX components as templates in Nodemailer. In my current setup for Nodemailer, I have to manually write the HTML template like this: html: ` <div style="h ...

Is there a way to circumvent the eg header along with its contents and HTML code using JavaScript?

I have a script in JavaScript that is designed to replace the content of data-src attribute within each img tag with src. However, I am facing an issue where this script interferes with the functionality of a slider located in the header section. The sli ...

Error message in Jquery function: Uncaught TypeError - undefined property 'noDisagree'

Hey there! I am attempting to invoke a function in an AngularJs controller with a parameter using Jquery, but unfortunately encountering the error: Uncaught TypeError: Cannot read property 'noDisagree' of undefined function noDisagree(id){ ...

Utilizing Next.js Router.push() triggers automatic page reloads

Is there a method to trigger a Router.push() without causing the page to refresh in Next.js? I have set up a main file named [...all].js for a page that displays different components based on the URL. However, I need to navigate between these components w ...

Using Javascript and HTML5 Canvas to retrieve dimensions of selected objects

I have a canvas with an image containing colored squares. I want to be able to click on a square and retrieve its dimensions in pixels. For instance, clicking on a red square with a yellow border should return 24 X 100. I've come across some code that ...

Using HTML to design interactive buttons that can send API requests and display their current status

Seeking assistance with creating buttons to control a remote light's ON and OFF states while reflecting their status as well. The specific http API calls for the light are necessary to toggle its state. Turn On = http://192.168.102.22:3480/data_requ ...

Utilizing Angular.js to nest directives seamlessly without cluttering the markup

Expressing my query might pose some difficulty, but I appreciate your patience. I comprehend that in the realm of Angular.js, directives play a crucial role in driving dynamic markup. What was once achieved through jQuery can now be accomplished using dir ...

The latest update to andt version 5.20.0 has encountered an issue with the FastColor.js file located in the node_modules. An error has been identified at line 56

After updating to the latest version of [email protected], I utilized npm i antd --save --legacy-peer-deps without any issues. However, upon running npm start, I encountered an error in the console. Is anyone else experiencing this problem? ERROR in . ...

Exploring JSON data for auto-complete suggestions

Upon receiving the object from the source, it looks like this - ["road",[["road",53,"0E"],["roadtrip",53,"1E"],["roadrunner",53,"2E"],["roadster",53,"3E"],["roadside",53,"4E"],["roadrage",53,"5E"],["roadcycling",53,"6E"],["roadsideamerica",53,"7E"]],{"k": ...

React Native - The Animated.spring function experiences a flickering issue when the animation is reverted

I am currently working on implementing a drawer in my react native app. The issue I am facing is with the closing animation. When I click the close button, the animation seems to blink or flicker, as if it is opening and closing multiple times before final ...

How come the function is being triggered by my onclick button as soon as the page loads?

Currently, I am experiencing a challenge in my NodeJS project with Express. The issue lies with my EJS client side file when it comes to handling button click events. In my EJS file, I have imported a function from a JS file and can invoke it using <% ...

Having issues with ng-repeat not displaying any content

Let me describe the current situation I am facing: app.controller('ResourceController', function($scope, $sce){ var resourceData; $scope.data = ''; $scope.loadResources = function(){ $.get('con ...

Harnessing the power of express middleware to seamlessly transfer res.local data to various routes

I am in the process of implementing a security check middleware that will be executed on the specific routes where I include it. Custom Middleware Implementation function SecurityCheckHelper(req, res, next){ apiKey = req.query.apiKey; security.securi ...

The JavaScript code appears to have malfunctioned as it abruptly terminates with an exit code of 1

When running the code, it reports that prompt-sync cannot be found and exits with error code 1 const input = require('prompt-sync')(); var firstName = input("Enter your first name:"); var lastName = input("Enter your last name:"); console.log(" ...

Utilizing Javascript to load and parse data retrieved from an HTTP request

Within my application, a server with a rest interface is utilized to manage all database entries. Upon user login, the objective is to load and map all user data from database models to usable models. A key distinction between the two is that database mode ...