How to import react component in lit component?

537 views Asked by At

I Have React component. Now i am trying to import React Component in Lit Component. But React component is either not getting rendered nor it is throwing any error in the console. Is there any way to import the react component in lit component.

1

There are 1 answers

0
Augustine Kim On

This is not possible as is since React components are not made to be interoperable like Web Components.

You would need to designate a root container for the React component inside the Lit component and use react-dom to render the React component in there.

Something like:

import {html, LitElement} from 'lit';
import {customElement} from 'lit/decorators.js';
import {createRoot} from 'react-dom/client';
import SomeReactComponent from './SomeReactComponent.js';

@customElement('my-element')
export class MyElement extends LitElement {
  #reactRoot;

  updated() {
    if (this.#reactRoot === undefined) {
      this.#reactRoot = createRoot(this.renderRoot!.querySelector('#root'));
    }
    this.#reactRoot.render(<SomeReactComponent />);
  }

  render() {
    return html`<div id="root"></div>`
  }
}

There have been ideas about making this easier like this issue proposing a base class to turn a React component into a web component.