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

  1. create a js class for your element which inherits from HTMLElement
    • define a constructor with call to super()
  2. 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

  1. connectedCallback() - called each time is appended into a document-connected element
    1. typically the place to add render behavior
    2. this is where to code dom apis
    3. attach to shadowRoot using: 
      1. shadow.innerHTML = `<p>hi<p>`;
      2. or: shadow.append(htmlFragment)
  2. disconnectedCallback() - called when disconnected form documents DOM
  3. observedAttributes() - used to specify list of attributes to watch
    1. for react folks think props
  4. attributeChangedCallback() - called when when one of the custom element's attributes is added, removed, or changed
    1. 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 shadowRoot

To 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

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more