Simple Web Components Hello World

Photo by Zosia Korcz on Unsplash

Simple Web Components Hello World

When learning its always good to start simple. As simple as possible. I think this is also a good approach for learning web components. For now I'm avoiding frameworks, compilers or any other complications. I'm trying to keep it as simple as possible so its just HTML, css and javascript. So here is my super simple and basic hello world web component.

    <script>
      class HelloWorld extends HTMLElement {
        constructor() {
          super();
          console.log("I work!");
        }
        connectedCallback() {
          this.innerText = "Hello world";
          this.style.color = "red";
          this.style.display = "block";
        }
      }

      customElements.define("hello-world", HelloWorld);
    </script>

Things to note

  • For simplicity sake I added the javascript directly to a script tag in the HTML.
  • Your component class needs to extend the HTMLElement class.
  • The constructor method and super function isn't needed for this simple example but I included it for reference.
  • connectedCallback is a web component lifecycle method called after the component is added to the DOM. This is where your logic can go in a simple component like this one.
  • In your class "this" refers to the DOM element you are creating.
  • I'm using "this" and javascript to change the component's text and css styles.
  • the customElements define function is what connects your web component to the HTML.

Want to play with my example? Check out my codepen. Next time I will tackle a more complicated component.