7 Web Components
This chapter covers
- The component design pattern
- Breaking a user interface into reusable units
- Building Vanilla Web Components
- A walkthrough of the Custom Elements API and Shadow DOM
- How to use CSS to style components
In the previous chapter, we covered how to use the DOM API to interact with a vanilla web user interface. In this chapter, we will begin with one of the most significant additions to the DOM API for creating maintainable, reusable applications: web components.
7.1 The component design pattern
The component design pattern breaks a user interface into small reusable parts that encapsulate structure, behavior, and style. They are everywhere in the app development world: in mobile native apps, desktop apps, and UI libraries. On a Vanilla web project, rather than sprinkling pieces of markup and script throughout a page, you define a component once and then reuse it wherever you need it.
Web Components are custom HTML elements that behave like built-in tags. They solve long-standing problems around code reuse by providing a built-in way to package markup, behavior, and styling together.