Creating a React Custom Element Wrapper Generator

A few days ago I published a post called “Wrapping React Components Inside Custom Element.” The post explained how to wrap a React component inside a custom element. At the end of the post, I wrote that I might think of a few ways to do the same functionality but automatic and more generic. In this post, I’ll explain one of those ideas.

Note: If you didn’t read the previous post, I suggest to read it to get some context for this post.

Observing Props

At first, I’ll take an assumption which is that the majority of React developers use the prop-types library to declare React prop types on their React component. Using this assumption, we can use the prop types to understand the names and the types of all the props that a component is receiving and to generate the observed attributes array for the custom element. We will create a getObserved helper function, which will be responsible to extract the names of the observed attributes from the prop types:

Wrapping React Components Inside Custom Elements

This week I had the pleasure of speaking in the ReactNext 2019 conference. My talk was called “I’m with Web Components and Web Components are with Me” and it was all about consuming Web Components in React apps and wrapping React components with custom elements. In this post, I’ll explain the second part and why you might want to do it. When the talk video will be available online, I’ll embed it in this post.

React and Web Components

In React documentation there is a section about React and Web Components. In that section, it is mentioned that React and Web Components are complementary to each other. While React is a view engine that is responsible for keeping the DOM in sync with the app's data, Web Components provide strong encapsulation for the creation of reusable HTML components. But in the real world most of the companies that I consult for don't use the two options together and why is that?