Introduction to Creating Web Components
As web apps get more complex, we need some way to divide the code into manageable chunks. To do this, we can use Web Components to create reusable components that we can use in multiple places.
Web Components are also isolated from other pieces of code so it’s harder to accidentally modify them from other pieces of code and create conflicting code.
In this article, we’ll look at the different parts of a Web Component and how to create basic ones.
Parts of a Web Component
A Web Component has 3 main parts. Together they encapsulate the functionality that can be reused whenever we like without fear of code conflicts.
- custom element — a set of JavaScript APIs that allow us to define custom elements and their behavior, which can be used as we desired in the UI
- shadow DOM — set of JavaScript APIs for attaching the encapsulated shadow DOM tree of the element. It’s rendered separately from the main document DOM. this keeps the element’s features private, so they can be scripted without the fear of conflicting with other parts of the document
- HTML templates — the
template
orslot
elements enable us to write markup templates that aren’t displayed on the rendered page. They can be reused multiple times as the basis of…