DEV Community

Max
Max

Posted on

Some tips for your first WebComponent

Over the last year I have been investigating various ways of making WebComponents. In this article I summarise what I have learnt in this process

1. Attributes with basic types

A prop is an input that can be added to WebComponents. Whenever possible, I recommend using a basic type: number, bool, string or number and avoiding Array and JSON types, although I understand that this may not be possible at times.

The problem with using an Array or JSON is that native HTML elements only allow basic attributes and there is no possible way to put an Array or JSON into an HTML template. Therefore, the only way (that I have found) is to instantiate the WC in the HTML and then reference that element in JS and add the Array or JSON attribute:

<!-- This won't work -->
<my-element my-prop-array="[1,2,3]"></my-element>
<my-element my-prop-json="{user: 'max'}"></my-element>

<!-- This will work -->
<my-element></my-element>
<script>
    document.querySelector("my-element").myPropArray = [1, 2, 3]
    document.querySelector("my-element").myPropJson = { user: "max" }
</script>
Enter fullscreen mode Exit fullscreen mode

Also, it should be noted that I have found that with certain frameworks such as Angular, it is necessary to do a JSON.stringify(myPropJson) and in the WC do a JSON.parse(myPropJson), which is not the best process in my opinion.

2. Reactive vs static

You have to know the difference between a reactive and a static WC prop:

  • Reactive: The value of the variable that is passed to the component and the value of the prop is always the same.
  • Static: A copy of the value of the variable passed to the component is created in the prop.

Depending on the framework you want to use, you must indicate what you want.

3. Output with events

The way to pass data from a WebComponent to the host is mainly through events. Note that these events may be encapsulated in a CustomEvent, where the detail attribute will have the value that has been emitted.

4. Working with styles

One of the positive aspects that WebComponents bring is the use of the Shadow DOM. This is a big plus point, but on the other hand, being something relatively new, CSS development should be at its most basic. If you try to do something more complex, for example with PostCSS, you might not work or you might have a lot of difficulties.

5. Use a template

It is better if you use a template when you start the development of a WebComponent, as these templates are usually configured to do the build as well. I have developed two templates with lit and vite:

Top comments (0)