web components and how we used
Web components
"Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps." - MDN
3 main technologies
- Custom elements: define behavior of the component
- Shadow DOM: a shadow dom is rendered separately from the main document dom, and thus isolated
- you can create a custom element with a shadow dom
- HTLM Templates write markup templates
steps to build your own web component
write the class
- create a js class for your element which inherits from HTMLElement
- define a constructor with call to super()
- register it with the CustomElementRegistry object e.g. customElements.define("word-count", WordCount, { extends: "p" });
- the extends is optional, but shows you can extend from existing elements and use like so: <p is="word-count">
- terminology update: when extending it called "Custom built in"
add behavior by adding lifecycle methods to your class
- connectedCallback() - called each time is appended into a document-connected element
- typically the place to add render behavior
- this is where to code dom apis
- attach to shadowRoot using:
- shadow.innerHTML = `<p>hi<p>`;
- or: shadow.append(htmlFragment)
- disconnectedCallback() - called when disconnected form documents DOM
- observedAttributes() - used to specify list of attributes to watch
- for react folks think props
- attributeChangedCallback() - called when when one of the custom element's attributes is added, removed, or changed
- notice you get the name as well as old and new values attributeChangedCallback(name, oldValue, newValue)
add styles
You can attach styles inline or as a link element to the shadowRootTo attach styles inline
- document.createElement("style");
- style.textContent = `.my-class { }`;
- shadow.append(syle, htmlFragment)
To attach styles as linked file
- link: document.createElement("link");
- shadow.appendChild(linkElem);
libraries to make this easier
Lit - https://lit.dev/
Stencil - https://stenciljs.com/
Here's a gist example use of web components to render html from another source in a shadow dom.
helpful resources
https://developer.mozilla.org/en-US/docs/Web/Web_Components
https://www.youtube.com/watch?v=vLkPBj9ZaU0
https://css-tricks.com/building-interoperable-web-components-react/
shadow dom: https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM
https://bradfrost.com/blog/post/lets-talk-about-web-components/?ck_subscriber_id=1697731036
Comments
Post a Comment