Search code examples
next.jsstyled-components

NextJS shows Warning: Prop className did not match when using Tailwind CSS and styled components


import { createContext, useEffect, useState } from 'react';

export const CartContext = createContext({});

export function CardContextProvider({ children }) {
  const [cartProducts, setCartProducts] = useState([]);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const localStorageData = window.localStorage.getItem('cartProducts');
      if (localStorageData) {
        setCartProducts(JSON.parse(localStorageData));
      }
    }
  }, []);

  useEffect(() => {
    if (typeof window !== "undefined") {
      window.localStorage.setItem('cartProducts', JSON.stringify(cartProducts));
    }
  }, [cartProducts]);

  function addProduct(productId) {
    setCartProducts([...cartProducts, productId]);
  }

  function removeProduct(productId) {
    const index = cartProducts.findIndex((id) => id === productId);
    if (index !== -1) {
      const newCartProducts = [...cartProducts];
      newCartProducts.splice(index, 1);
      setCartProducts(newCartProducts);
    }
  }

  return (
    <CartContext.Provider value={{ cartProducts, setCartProducts, addProduct, removeProduct }}>
      {children}
    </CartContext.Provider>
  );
}

enter image description here

What can cause this warning? I tried to avoid all things presented here and I am still encountering this error. I am using next.js, tailwind and styled components.


Solution

  • Problem :

    Nextjs hydration : cannot write a title without error

    Possible Cause :

    • Browser Extensions
    • Using browser-only APIs like window or localStorage in your rendering logic & not using 'use client' directive
    • Improper next.config.js

    Possible Solution :

    • Add 'use client' directive at top of file in CardContextProvider

    • Disable all browser extensions,

    Add styledComponents: true, in next.config.js :

    /** @type {import('next').NextConfig} */
    
    const nextConfig = {
      ...
      compiler: {
        styledComponents: true,
      },
    };
    
    module.exports = nextConfig;
    

    Please Read :

    If you have any doubts, then please leave a comment (I will update answer if necessary)