Vinay Dhakre
Vinay Dhakre

Reputation: 61

How to import react component in lit component?

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.

Upvotes: 1

Views: 1925

Answers (2)

Philip
Philip

Reputation: 3536

I have also looked into this and have now come to this conclusion.

import { Button } from 'components/button';
import styles from 'button.css?inline';
import { LitElement, unsafeCSS } from 'lit';
import { customElement } from 'lit/decorators.js';

import React from 'react';
import { createRoot } from 'react-dom/client';

@customElement('my-button')
export class MyButton extends LitElement {
  connectedCallback() {
    super.connectedCallback();
    createRoot(this.shadowRoot).render(<Button dangerouslySetInnerHTML={{ __html: this.innerHTML }}></Button>);
  }

  static styles = unsafeCSS(styles);
}

Upvotes: 0

Augustine Kim
Augustine Kim

Reputation: 1186

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.

Upvotes: 2

Related Questions