Web Components

webc/constructor-no-attributes

A custom element constructor never reads or adds attributes or children; do that in connectedCallback.

seriousstaticfe-web-components

Why

An element made with document.createElement('acme-card') has no attributes and no children while its constructor runs, so reading them gives null. Adding them makes the creation fail: createElement throws, and so do frameworks that create elements this way. The element then works when written in HTML and breaks when a framework renders it.

Fix

In the constructor only call super(), set default state, attach the shadow root and add listeners. Read attributes in connectedCallback or attributeChangedCallback (list them in observedAttributes), and set a default role or state through ElementInternals (this.internals.role = 'button') instead of adding attributes to the host.

Examples

// bad
constructor() {
  super()
  this.setAttribute('role', 'button')
  this.label = this.getAttribute('label')
}
// good
constructor() {
  super()
  this.internals = this.attachInternals()
  this.internals.role = 'button'
  this.attachShadow({ mode: 'open' })
}
connectedCallback() { this.label = this.getAttribute('label') }

Sources

Facts

Id
webc/constructor-no-attributes
Severity
serious
Check
static checked in the source by audit
Applies to
jsx html
Taught by the skill
fe-web-components Web components and Lit
Since version
0.1.0

Rule file on GitHub

Read it in the terminal

npx github:dawidolko/frontend-skills explain webc/constructor-no-attributes