This is a very challenging space with multiple moving parts. React is not super friendly to DSD when hydrating. The Lit team has created packages to try to make things "play nice" but as we shall see, this is not smooth sailing.
Heres a simple Lit element component that we register as my-web-component.
import { LitElement, html, css } from "lit";
export class MyWebComponent extends LitElement {
static styles = css`
.heading {
color: #15156d;
font-family: Arial, Helvetica, sans-serif;
}
`;
render() {
return html`<h1 class="heading">My server rendered web component</h1>`;
}
}
customElements.define("my-web-component", MyWebComponent);
We then wrap it using @lit/react
import React from 'react';
import { createComponent } from '@lit/react';
import { MyWebComponent } from './my-web-component.js';
export const MyWrappedWebComponent = createComponent({
tagName: 'my-web-component',
elementClass: MyWebComponent,
react: React
});
and finally we use it in our React app. We import @lit-labs/ssr-react/enable-lit-ssr.js
to get things to
work properly in the Node.js context.
import React from "react";
import '@lit-labs/ssr-react/enable-lit-ssr.js';
import { MyWrappedWebComponent } from './my-wrapped-component.js';
function App() {
return (
<div className="App">
This is a test
<MyWrappedWebComponent />
</div>
);
}
export default App;
Now, when we SSR our React app, everything works nicely!
Unfortunately, this solution won't work in Next v13 or above and theres currently no solution from the Lit team though they plan to look into it.
See