chapter four

4 Best practices

 

This chapter covers

  • Established patterns for developing web components
  • A sample web component that demonstrates each practice
  • A project that shows how to use the example component

The website web.dev provides a checklist of Custom Element Best Practices. These best practices provide tips for improving the quality of your web components, and they’re an invaluable resource for any developer working with web components. This chapter builds on that checklist by adding TypeScript code examples. We provide details on the support provided by the web component libraries covered in this book: Lit, Stencil, FAST, and wrec.

These practices were developed and refined by software developers who work closely with the modern web platform, drawing on real-world experience building and maintaining web applications. In this chapter, you’ll learn about each of the best practices, and why you should follow them.

Many of these practices focus on ensuring that custom elements encapsulate their styling and functionality, integrate cleanly with HTML and CSS semantics, respond correctly to attribute and property changes, and properly dispatch events.

In the following sections, we’ll walk through each best practice and demonstrate how to follow it. To do this, we’ll gradually build a vanilla sortable-table web component to highlight each best practice in action.

4.1 Example component

Let’s start by introducing the project we’ll be working on: a sortable-table.

4.2 Best practices

4.2.1 Create a shadow root to encapsulate styles

4.2.2 Create your shadow root in the constructor

4.2.3 Place any children the element creates into its shadow root

4.2.4 Use <slot> to project light DOM children into your shadow root

4.2.5 Set a :host display style unless you prefer the default of inline

4.2.6 Add a :host display style that respects the hidden attribute

4.2.7 Do not override author-set, global attributes

4.2.8 Always accept primitive data as either attributes or properties

4.2.9 Aim to keep primitive data attributes and properties in sync, reflecting from property to attribute, and vice versa

4.2.10 Aim to only accept rich data (objects, arrays) as properties

4.2.11 Do not reflect rich data properties to attributes

4.2.12 Consider checking for properties that may have been set before the element upgraded

4.2.13 Do not self-apply classes

4.2.14 Dispatch events in response to internal component activity

4.2.15 Do not dispatch events in response to the host setting a property

4.4 Summary