Reflecting Properties to Attributes
You'll learn how to keep JavaScript properties and HTML attributes in sync using getters and setters.
The Two-Way Street Problem
When you create a custom element, you have two ways users can configure it: JavaScript properties (element.value = 'hello') and HTML attributes (<my-element value="hello">). By default, these don't stay synchronized—changing one doesn't affect the other. Reflecting means writing code to keep them in harmony.
Core Idea
Use getters and setters in your custom element class to intercept property access. When someone sets a property, your setter updates the corresponding attribute. When they read the property, your getter returns the current attribute value.
class MyInput extends HTMLElement {
// Getter reads from the attribute
get value() {
return this.getAttribute('value') || '';
}
// Setter updates the attribute (reflection!)
set value(newValue) {
this.setAttribute('value', newValue);
}
}
customElements.define('my-input', MyInput);
Now both approaches work identically:
const input = document.querySelector('my-input');
input.value = 'test'; // Updates the attribute too!
console.log(input.getAttribute('value')); // 'test'
Why This Matters
Reflection ensures consistent behavior whether users interact with your element via JavaScript or HTML. It also triggers attributeChangedCallback when properties change, keeping your reactive system working smoothly.
Think of It As...
Imagine a thermostat with both a dial and a smartphone app. Reflection is like making sure turning the dial updates the app, and changing the app updates the dial—they always show the same temperature.
Key Takeaway: Use getters and setters to reflect JavaScript properties to HTML attributes, ensuring your custom element's state stays consistent regardless of how it's accessed.