How to: Create a web component in ReactJS

Riccardo Canella
Javascript by doing
4 min readNov 17, 2021

--

In recent times, fortunately, web components are gaining ground and are being used more and more. I personally am very happy with it and I hope to be able to make more use of it also in my day-by-day job.

But, what are web components?

Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. Custom components and widgets build on the Web Component standards, will work across modern browsers, and can be used with any JavaScript library or framework that works with HTML.

Web components are based on existing web standards. Features to support web components are currently being added to the HTML and DOM specs, letting web developers easily extend HTML with new elements with encapsulated styling and custom behavior.

[web components]… can be used with any JavaScript library or framework that works with HTML.

We can extend this premise, taken directly from webcomponent.org, where you can find in addition to a better explanation of what web components are also many examples and resources, also saying that they can be created using any framework that works with HTML. Today we will focus on how to create a web component using ReactJS.

You can find the code on this github repo! It is a monorepo managed with Lerna because it will also contain other examples with several other frameworks, if you want to see directly the one in ReactJS here at this link: thecreazy/framework-webcomponents/tree/main/packages/webcomponent-react

Let’s start coding

Create a base component [0e49349]

For this example we will create a simple counter, our counter will:

  • Present value
  • A button to increase the value by one
  • A button to decrease the value by one
  • Will send events when the value changes
  • Will send event when the increment button is pressed
  • Will send event when the decrement button is pressed

--

--

Riccardo Canella
Javascript by doing

Riccardo Canella @ricanella92 Love #basket, #bike and #HIMYM since my childhood. #Fullstack #Javascript addicted - https://canellariccardo.it