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 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.
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