Web components: The ultimate guide
Discover the benefits of web components, how they work, and how to get started using them today.
While there are a lot of complicated things you can achieve with web components, simply getting up and running actually involves very little code. Take your first steps into web components with a couple of short examples.
This first tutorial (below) focuses on building a component to display user comments by making use of the HTML templates and shadow DOM APIs.
Jump to page 3 to learn how to save yourself time by using custom elements.
01. Provide a template
The component needs a generic template it can copy in order to generate its markup. This can live anywhere that the custom element class itself can access through its unique ID.
Add the <template> element directly in the HTML of the page. Any styles written here will only affect the component.
<template id="user-comment-template">
<style>
[…]
</style>
</template>
02. Add in markup
Along with the styles, the template contains the structure of the component's internals. In this case, it is set of <div> containers for layout purposes.
All dynamic content is passed in through slots. Add in slots for the user's avatar, name and message, and give them appropriate names to reference later.
Get top Black Friday deals sent straight to your inbox: Sign up now!
We curate the best offers on creative kit and give our expert recommendations to save you time this Black Friday. Upgrade your setup for less with Creative Bloq.
<div class="container">
<div class="avatar-container">
<slot name="avatar"></slot>
</div>
<div class="comment">
<slot name="username"></slot>
<slot name="comment"></slot>
</div>
</div>
03. Default slot content
The data passed into the slot will override whatever sits inside it in the template. If there is nothing supplied for that slot, it displays the fallback content instead.
In this case, if no username is supplied, the comment will display a 'no name' message in its place.
<slot name="username">
<span class="unknown">No name</span>
</slot>
04. Create the class
Custom elements start life as a class that extends the generic HTMLElement class. As part of the setup process, it creates its own shadow root to render its content into. Keep it open in order to access it in the next step.
Finally, tell the browser about the new UserComment component class.
class UserComment extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
}
}
customElements.define("user-comment",
UserComment);
05. Apply shadow content
When the browser finds a <user-comment> element, it is going to populate the shadow root with the content of the template. The second argument tells the browser to copy all of the template, not just the first layer.
Add that markup to the shadow root, which will immediately update the visuals of this component.
connectedCallback() {
const template = document.getElementById
("user-comment-template");
const node = document.importNode(template.
content, true);
this.shadowRoot.appendChild(node);
}
06. Use the component
Back in the HTML, the component is now ready to use. Add the <user-comment> tag and add any relevant data inside.
As all slots are named, anything else that is passed through outside of a slot will be ignored. Everything inside those slots is copied in exactly as supplied, including related styling.
<user-comment>
<img alt="" slot="avatar" src="avatar.png" />
<span slot="username">Matt Crouch</span>
<div slot="comment">This is an example of
a comment</div>
</user-comment>
Next page: How to create a customised built-in element
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
Current page: Build your own components
Prev Page The 4 pillars of web components Next Page Create a customised built-in elementMatt Crouch is a front end developer who uses his knowledge of React, GraphQL and Styled Components to build online platforms for award-winning startups across the UK. He has written a range of articles and tutorials for net and Web Designer magazines covering the latest and greatest web development tools and technologies.