Bryan Primus Lumbantobing
Posted on September 13, 2021
Thumbnail source: itnext
Let's start with the Definition of Web Components.
Based on webcomponents.org:
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 built on Web Component standards work across modern browsers and can be used with any JavaScript library or framework that works with HTML.
From this definition, we know that using web components allows us to create reusable components for any project that uses HTML. Web components are essentially a set of custom HTML tags.
So why does this matter, and what are the advantages of building a project with web components? Why not just use a popular framework or library?
Well, that's the beauty of web components: any framework that builds and uses HTML can support web components.
Back to why this matters:
We're not going to cover every advantage here. Instead, we’ll focus on one interesting aspect.
Shared Resource & Scoping
Using web components allows us to scope resources within our application while sharing them across other web applications.
Imagine you're building a library that isn’t specifically targeted at any framework or library. This can be extremely useful.
For Example in a React Application
We can include web components in React because React uses HTML to render components.
Consider this example:
class HelloMessage extends React.Component {
render() {
return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
}
}
In the example above, we can easily add a web component within a React application. One thing to note is that web components use class instead of className.
We can also go the opposite way by adding React components to web applications that use web components.
How to Write a Web Component
class XSearch extends HTMLElement {
connectedCallback() {
const mountPoint = document.createElement('span');
this.attachShadow({ mode: 'open' }).appendChild(mountPoint);
const name = this.getAttribute('name');
const url = 'https://www.google.com/search?q=' + encodeURIComponent(name);
ReactDOM.render(<a href={url}>{name}</a>, mountPoint);
}
}
customElements.define('x-search', XSearch);
The example above shows how to create a web component. It’s a class that extends HTMLElement and isolates the scope of the element using a shadow DOM. This way, the scope is separate from other components.
connectedCallback
is one of the lifecycle methods in web components and runs before the component is rendered.
There are still configurations required to run a web component. A basic understanding of Webpack is recommended to configure the app.
That’s it!
To learn more about web components:
Next: Start building a project using web components or turn a React project into web components.
Posted on September 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.