DEV Community

Gil Fink
Gil Fink

Posted on • Originally published at Medium on

Creating a React Custom Element Wrapper Generator

Web Components

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:

Defining The Custom Element Wrapper Generator

At first, we will create the generator function definition, which will receive the React component class/function and the name of the custom element:

export const defineReactComponent = (Component, name) => {
   ...
}

After we created the generator function, in the function we will extract the observed attributes name from the component and then create the custom element class. At the end of the function, we will define the new custom element in the CustomElementRegistry. Here is the whole function implementation:

If you read my previous post most of this implementation should be familiar. A few things to notice:

  • We set the observed attributes array at the beginning of the function.
  • The generateAllProps function will be responsible to copy all the attributes to the props object which is passed to the React component. This solution is naive and isn’t covering things like data structures or functions. I’ll give you the opportunity to continue from here and build a more robust solution.

The end solution:

Summary

In the post, I converted a specific solution I used in the “Wrapping React Components Inside Custom Element” post to a more generic implementation to wrap the React component inside a custom element. I hope that this starting point will help you to go forward and create a more robust solution.

Let me know what do you think in the comments.

Top comments (0)