Search code examples
custom-elementpreact

Can I use a Preact component via Custom Elements?


I'd like to create a Preact component and let folks consume it, even if they're not building Preact apps.

Example: I'd like to build a <MyTooltip> component in Preact, bundle it (along with the Preact runtime), and have folks load it as a script tag use it purely declaratively, perhaps like:

<script src="https://unpkg.com/my-tooltip/my-tooltip-bundled.js">

<my-tooltip content="Tooltip content">Hover here</my-tooltip>

Is there a way to bundle up a component such that it includes the Preact runtime, my library code, and hooks into <my-tooltip> elements?

In other words, can I interop my Preact components as Custom Elements, similar to ReactiveElements?


Solution

  • There's a great library that does this for you called preact-custom-element:

    https://github.com/bspaulding/preact-custom-element

    class SearchBox extends Component {
      render() {
        // ...
      }
    }
    registerComponent(SearchBox, 'search-box');