If we are used to developing frontend components using a framework like React, we would want to be able to write a template for a function. Here is an example of a React component for rendering a Link in the UI:
Once I’ve defined my component definition once, I can use it everywhere inside of my application.
I then expect that at runtime, my app will render the link with my specified properties and I will get valid HTML:
Now we come to custom elements.
Once a browser triggers our
connectedCallback() method, we expect that our HTML would appear as follows:
Yes. It would look something like the following code:
But notice here that the actual templating for the HTML for the component is not done in the custom element itself (e.g. the
This is because the custom element specification was never intended to be used for templating!
In fact, that is probably the reason that there is a whole other part of the Web Components specification which is specifically for Templates.
By combining both custom elements and templates, we could build a component which performs templating at runtime.
I’ve used both of these approaches for lightweight templating within custom elements, although I personally prefer template strings because they feel less unwieldy than HTML templates for this use case.
What custom elements are actually good at
I’ve now discussed in detail what custom elements are NOT good at, and now I want to look at where they excel.
a) tag with the class
replace-link) has already been loaded. If that is not the case, then the component will not be initialized correctly. Additionally, if HTML code containing the component is added to the page after the initialization function has been executed, these components will also not be initialized correctly. Our example component replaces a link element on a page with the content of the page that the link points to – if that content also includes an instance of the component within the page, the component will not be initialized unless we remember to call the initialization function after loading the HTML.
In my opinion, this is the main problem that custom elements solve. We can define the initialization logic for our component within the
In this example, we can also see the second major benefit of using custom elements: because a custom element extends
HTMLElement will be bound to the
this variable within the class. This means that I can use
this.querySelector("a") to retrieve a link element which is contained within the element in the DOM or any of the other useful properties and methods available for an
Look at how we can use our new
replace-link custom element in our HTML: