How to Create and Export Web Components From a React Application

Recently, I worked on a project to rewrite a legacy software system. After we began active development, we realized could solve some acute needs of the system with some of the features that we were building. We weren’t ready to release the whole application, but we wanted to release some of the new features we’ve built.

So, we worked through that problem: exporting a handful of components from our React application for use in a Vue web application. When I first started looking into it, I had no idea where to begin, other than assuming I’d need to wrangle with Webpack. But, after a few conversations with colleagues, discovered Web Components.

Web Components to the Rescue

From the docs on MDN:

Web Components aims to solve such problems — it consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions.

The React component can be registered as a Web Component. Another application (or just a plain HTML page) can then import and use that Web Component. With this approach, components are encapsulated within a shadow DOM and can’t interfere with the rest of the application.

This sounded like a perfect fit for our needs.

Creating our Web Component

React includes tools for creating and registering a Web Component, and we can use them in conjunction with our build tools. In the following example, I’m going to use Webpack. The full code is available on GitHub.

import * as React from "react";
import * as ReactDom from "react-dom";
import { FetchData } from "./fetch-data";

class StandaloneComponent extends HTMLElement {
  mountPoint!: HTMLSpanElement;
  name!: string;

  connectedCallback() {
    const mountPoint = document.createElement("span");
    this.attachShadow({ mode: "open" }).appendChild(mountPoint);

    const name = this.getAttribute("name");
    if (name) {
      ReactDom.render(<FetchData name={name} />, mountPoint);
    } else {
      console.error("You must declare a name!");
    }
  }
}
export default StandaloneComponent;

window.customElements.get("standalone-component") ||
  window.customElements.define("standalone-component", StandaloneComponent);

A few things are going on in here, though some are just a byproduct of the React and Web Component API. We must declare the class and extend the HTMLElement. We need to create a mountPoint and specify that we’re attaching it to the shadow DOM. And, finally, we need to define our Web Component (we don’t need to redefine it if we already have). For our custom component, we require a name prop, and we can access it via the HTML “attributes” for prop-like parity.

I’ll include some of the relevant Webpack configuration below, but feel free to refer to the GitHub repo for more details. This may not be relevant to your build configuration, whether it’s Webpack, ESBuild, or something else. However, I’ve tried to highlight a few of the differences between our client Webpack configuration.

module.exports = {
  // much of this is shared with webpack/client.config.js, but for simplicity, we are removing any chunking / minimizing / code splitting / other optimization and we have no need for HtmlWebpackPlugin or the devServer.
  entry: {
    app: ["./src/standalone.tsx"],
  },
  output: {
    path: path.resolve(__dirname, "../dist/standalone"),
    publicPath: `${JSON.stringify(config.get("server.publicHost"))}/standalone`, // looks like http://localhost:3000/standalone when running locally
    filename: "client.js",
  },
};

The deployment and distribution process must be easy to use. Therefore, we want to be able to serve the JavaScript bundle on a web server, rather than building it into another web application.

We can do that pretty easily with Express:

const port = process.env.PORT || 3001;

let app = express();

// other API endpoints

// serve the dist directory, where our standalone component is built
app.use(express.static("./dist/"));

app.listen(port, () => {
  console.info("up and running on port", port);
});

And we can use our script like:

<html>
  <head>
    <script src="http://localhost:3001/standalone/client.js"></script>
  </head>

  <body>
    <standalone-component name="Web Component" />
  </body>
</html>

Including a script tag will fetch the JavaScript and register the Web Component, which allows us to run our component later in the page. Of course, we can follow a similar pattern in other languages and JavaScript frameworks, but I find that it’s easiest to boil this down to the most simple case and stick with HTML when testing this out.

Conversation
  • Anubhav jha says:

    How the hell do you manage adding css in the web component?

  • Join the conversation

    Your email address will not be published. Required fields are marked *