Greg
Greg

Reputation: 31378

WebComponents and NextJS - Error: Hydration failed because the initial UI does not match what was rendered on the server

I'm encountering the following error message:

Error: Hydration failed because the initial UI does not match what was rendered on the server.

This issue arises when running a NextJS web page containing StencilJS web components. StencilJS offers the capability to encapsulate its distributable components within React components, which proves advantageous when utilising them in a React app. For instance:

<div className="control">
  <label className="button icon secondary">
    <DmeIconCross class="close" />
    <DmeIconMenu class="open" />
    <input className="menu" type="checkbox" />
  </label>
</div>

Here, DmeIconCross and DmeIconMenu represent web components wrapped in React proxies.

The source of the problem lies within these web components, as indicated by the accompanying warning:

Warning: Did not expect server HTML to contain an <svg> in <dme-icon-cross>.

The web components, during hydration, incorporate SVG icons.

I am seeking guidance on potential configurations or instructions to advise NextJS to either disregard or navigate around this particular behaviour.

Upvotes: 0

Views: 79

Answers (1)

Greg
Greg

Reputation: 31378

To solve this problem I found a specific entry in the documentation in NextJS.

It's not the prettiest solution but it's simple enough to understand how this is instructing NextJS that this component is specifically a client side web component and will deal with it's own hydration.

import dynamic from 'next/dynamic';

const DmeIconCross = dynamic(
  () => import('@design-system/libs/react').then(mod => mod.DmeIconCross),
  { ssr: false },
);

...

export function Page() { ...

Docs - https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-no-ssr

Upvotes: 0

Related Questions