<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dénes Máté Bencze on Medium]]></title>
        <description><![CDATA[Stories by Dénes Máté Bencze on Medium]]></description>
        <link>https://medium.com/@denesmb?source=rss-68d0f736e5b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l2M1nRTL2nKLzHXd3QTucA.jpeg</url>
            <title>Stories by Dénes Máté Bencze on Medium</title>
            <link>https://medium.com/@denesmb?source=rss-68d0f736e5b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:21:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@denesmb/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Native Web Component with LitElement  ]]></title>
            <link>https://medium.com/@denesmb/building-a-native-web-component-with-litelement-599fa5ca6e67?source=rss-68d0f736e5b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/599fa5ca6e67</guid>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[litelement]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dénes Máté Bencze]]></dc:creator>
            <pubDate>Mon, 25 Mar 2019 01:58:15 GMT</pubDate>
            <atom:updated>2023-02-23T03:37:38.138Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Native Web Component with LitElement 🔥</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*91oMpWJMt2IC5f5HllddoQ.png" /><figcaption>Keyword Tag Component</figcaption></figure><h3>Web Components</h3><p>“Web Components” is a series of specifications for extending the default set of HTML elements. These custom elements can be used by any HTML page or web application. Web components are supported by all major browsers, and custom elements <a href="https://custom-elements-everywhere.com/">work quite well</a> with the most popular front-end frameworks.</p><h3>Creating Custom Elements</h3><p>Custom elements can be created simply by extending the built-in <strong><em>HTMLElement</em></strong> class. Then, the new element can be registered in the browser’s <em>Custom Element Registry</em> with a new tag, using the <strong><em>customElements</em></strong> API, such as in this example:</p><pre><strong>class</strong> AwesomeButton <strong>extends</strong> HTMLElement {<br>   // Component definition goes here.<br>}</pre><pre>customElements.define(&quot;awesome-button&quot;, AwesomeButton);</pre><p>This is the vanilla way of defining custom elements, however, it’s more common to use a library that gives extra features and makes component development easier. Some of these libraries are <a href="https://stenciljs.com/">Stencil</a>, <a href="https://slimjs.com/">Slim.js</a> and Google’s <a href="https://lit-element.polymer-project.org/">LitElement</a>, which is built by the <a href="http://Polymer Project https://www.polymer-project.org/">Polymer</a> team.</p><p>LitElement is a super lightweight base class for web components, using native web and Javascript standards, such as the Custom Elements API, the Shadow DOM, and JS template literals. Similar to React, the UI structure can be expressed declaratively, as a function of the component state, however, instead of JSX, LitElement uses <a href="https://lit-html.polymer-project.org/"><em>lit-html</em></a> to define and render HTML templates.</p><p>In this tutorial, we’ll build a simple <strong>keyword tag</strong> as a native web component, using LitElement. We will use NPM for dependency management, and Typescript as our language.</p><h3>Component Requirements</h3><p>First, let’s define our component specification. We would like to build a simple keyword tag, that can be later used by a keyword editor. The component should display a single keyword, and a small, clickable “×” icon to remove itself from the set. It should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vriQymiNL_pCD03ZEuTmfQ.png" /><figcaption>Keyword Tag Component Mockup</figcaption></figure><p>The element needs a <strong>keyword</strong> string as an input, and it emits a <strong>removeClicked</strong> event along with the keyword, when the user clicks on the remove icon. This will be our simple component interface. Let’s get started! 🔥</p><h3>Setting up the Development Environment</h3><p>For this tutorial, let’s just use <a href="https://www.stackblitz.com/">StackBlitz</a>. It’s an online IDE for web applications, powered by Visual Studio Code. It automagically takes care of:</p><ul><li>installing our NPM dependencies,</li><li>compiling our project,</li><li>importing our code into the HTML page, and</li><li>serving the website and hot-reloading.</li></ul><p>Welcome to 2019, you don’t even need to leave the browser. 🎉</p><blockquote><a href="https://stackblitz.com/fork/typescript">Click here to get started with a new Typescript project.</a></blockquote><h3>Adding Dependencies and our index.html</h3><p>To build a web component using LitElement, first, we need to add it to our dependencies. To make sure that our component will work in unsupported browsers too, we should also add <em>webcomponentsjs</em>, which contains all the necessary polyfills. As of writing this article, the latest versions are 2.1.0 and 2.2.7, respectively. Change the name of the package, and add the following dependencies to our <strong>package.json</strong> file:</p><ul><li>“<strong>lit-element</strong>”: “2.1.0”,</li><li>“<strong>@webcomponents/webcomponentsjs</strong>”: “2.2.7”.</li></ul><pre>/// package.json</pre><pre>{<br>   &quot;name&quot;: &quot;my-web-components&quot;,<br>   &quot;version&quot;: &quot;0.0.1&quot;,<br>   &quot;private&quot;: true,<br>   &quot;dependencies&quot;: {<br><strong>      &quot;lit-element&quot;: &quot;2.1.0&quot;,<br>      &quot;@webcomponents/webcomponentsjs&quot;: &quot;2.2.7&quot;<br></strong>   }<br>}</pre><p>Let’s create our <strong>index.html</strong>, and import the polyfills using <em>script</em> tags, to support old browsers. Also, let’s add some heading to make sure our page preview updates properly.</p><pre>&lt;!doctype html&gt;<br>&lt;<strong>html</strong>&gt;</pre><pre>&lt;<strong>head</strong>&gt;<br>    &lt;<strong>script</strong> src=&quot;/node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js&quot;&gt;&lt;/script&gt;<br>    &lt;<strong>script</strong> src=&quot;/node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js&quot;&gt;&lt;/script&gt;<br>    &lt;<strong>title</strong>&gt;Web Components Example&lt;/<strong>title</strong>&gt;<br>&lt;/<strong>head</strong>&gt;</pre><pre>&lt;<strong>body</strong>&gt;<br>    &lt;<strong>h1</strong>&gt;LitElement Keyword Tag 🔥&lt;/<strong>h1</strong>&gt;<br>&lt;/<strong>body</strong>&gt;</pre><pre>&lt;/<strong>html</strong>&gt;</pre><blockquote><strong>Note</strong>: The <strong>index.ts</strong> file in our project will automatically be compiled and imported for us by StackBlitz, otherwise we would need to take care of it ourselves. Of course, in production, components should be <strong>lazy-loaded</strong> as they’re rendered.<em> ☝🏼</em></blockquote><h3>Building the Component</h3><p>Let’s add a new <strong>keyword-tag.ts</strong> file to our project. We need to import the following dependencies:</p><ul><li><strong>LitElement</strong> — the base class of our custom element,</li><li><strong>customElement</strong> — a class decorator that takes care of registering our component in the browser’s Custom Element Registry.</li></ul><p>Then, let’s add, and export our component class, which extends LitElement. Let’s use the <strong>customElement</strong> class decorator to register our component as “<em>keyword-tag</em>”. Please note that custom element names <em>must</em> include a hyphen, <a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define#Syntax">by definition</a>.</p><p>So far, our <strong>keyword-tag.ts</strong> should look like this:</p><pre>/// keyword-tag.ts</pre><pre><strong>import</strong> { LitElement, customElement } <strong>from</strong> &quot;lit-element&quot;;</pre><pre><strong>@customElement</strong>(&#39;keyword-tag&#39;)<br><strong>export</strong> <strong>class</strong> KeywordTag <strong>extends</strong> LitElement {</pre><pre>}</pre><blockquote><strong>Note</strong>: Decorators are still experimental features of Typescript. Please enable the <strong>experimentalDecorators</strong> compiler option in your <strong>tsconfig.json</strong> file.</blockquote><h4>Component Properties</h4><p>Properties are the inputs of components, now we have only one: the <strong>keyword</strong> string we would like to display. Let’s add this as a class property, along with the <strong>property</strong> decorator. The decorator is needed to identify <strong>keyword</strong> as part of the component state. As such, it will be observed, and the element’s <em>relevant parts</em> will be re-rendered, when there’s a new value. We also specify the property type in the decorator’s parameter — see <a href="https://lit-element.polymer-project.org/guide/properties#conversion-type">here</a> why.</p><pre>/// part of keyword-tag.ts</pre><pre><strong>@customElement</strong>(&#39;keyword-tag&#39;)<br><strong>export</strong> <strong>class</strong> KeywordTag <strong>extends</strong> LitElement {</pre><pre>   <strong>@property</strong>({ type: String })<br>   keyword = &quot;&quot;;</pre><pre>}</pre><h4>Component Template</h4><p>Now, let’s add a <strong>render</strong> function to our component. Optimally, the <strong>render</strong> function is a <em>pure function</em> of the component state. The function returns a <em>lit-html</em> template result. <a href="https://lit-element.polymer-project.org/guide/templates#template-syntax-cheat-sheet">Here’s a cheat sheet</a> for the template literal syntax. 😉</p><pre>/// part of keyword-tag.ts</pre><pre>render() {<br>   <strong>return</strong> html`<br>      &lt;<strong>div</strong> class=&quot;tag&quot;&gt;<br>         &lt;<strong>span</strong> class=&quot;word&quot;&gt;<br>            ${this.keyword}<br>         &lt;/<strong>span</strong>&gt;<br>         &lt;<strong>span</strong> class=&quot;remove-icon&quot;&gt;<br>            ×<br>         &lt;/<strong>span</strong>&gt;<br>      &lt;/<strong>div</strong>&gt;<br>   `;<br>}</pre><p>There’s a couple of things to mention here.</p><p>Note that we’re using a standard, tagged template literal. Similar to JSX, we can add expressions — for example, component properties, conditions, and loops. <a href="https://medium.com/@lucamezzalira/a-night-experimenting-with-lit-html-585a8c69892a">Here’s a great article</a> that compares the rendering performance of Preact and lit-html.</p><p>Also, everything returned by the render function will be rendered into the component’s shadow DOM, under the host element &lt;keyword-tag&gt;. Therefore, all CSS class names will be scoped to the component’s shadow root, so we don’t need to worry about name collision and style leaks. Read more about the Shadow DOM <a href="https://developers.google.com/web/fundamentals/web-components/shadowdom">here</a>.</p><h4>Component Styles</h4><p>There are 3 ways to style components: in a <em>static </em><strong><em>styles</em></strong><em> property</em> of the component class (this is recommended), inside a <em>&lt;style&gt; element</em> in the component’s HTML template, or in a <em>dedicated stylesheet</em>, referenced by the component’s template by a &lt;link&gt; tag. All 3 methods have their advantages, you can find more information about them <a href="https://lit-element.polymer-project.org/guide/styles#where">here</a>.</p><p>Now, we will define the component styles in a <em>static </em><strong><em>styles</em></strong><em> property</em>, which is the recommended way. This is a static function that returns a lit-html CSS result. After importing <strong>css</strong> from <strong>“lit-element”</strong>, let’s add the static <strong>styles</strong> function to our component class:</p><pre>/// part of keyword-tag.ts</pre><pre><strong>static</strong> <strong>get</strong> styles() {<br>   <strong>return</strong> css`<br>      :host {<br>         display: inline-flex;<br>         cursor: default;<br>      }</pre><pre>      .tag {<br>         display: flex;<br>         flex-direction: row;<br>         align-items: center;</pre><pre>         padding: 5px 10px;<br>         border-radius: 20px;</pre><pre>         background-color: #2196F3; /* fallback */<br>         background: linear-gradient(115deg, #2196F3 0%, #8FCDFF 100%);<br>         /* LitElement colors :) */</pre><pre>background-attachment: fixed;<br>         /* This will give a cool effect. :) */</pre><pre>font-size: 0.8rem;<br>         color: #FFFFFF;<br>      }</pre><pre>      .word {<br>         font-weight: bold;<br>         text-transform: lowercase;<br>      }</pre><pre>      .remove-icon {<br>         padding: 3px;<br>         cursor: pointer;<br>         margin-left: 5px;<br>      }<br>   `;<br>}</pre><p>The <strong>:host</strong> selector will select our component’s shadow root, the &lt;keyword-tag&gt; element. Styles in this rule are “visible”, and can be easily overridden from outside.</p><blockquote><strong>Note</strong>: The styles defined here can be changed by the component’s users in multiple ways. For example, inheritable CSS properties (such as font-size, by default) pierce the shadow DOM boundary. The common practice for letting users configure the component’s internal styles is to use <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties">custom CSS properties (a.k.a. CSS variables)</a>. The values of these properties also go through the shadow DOM boundary.</blockquote><p>Read more <a href="https://lit-element.polymer-project.org/guide/styles">here</a> about shadow DOM styling, both as a component developer and consumer.</p><h4>Component Events</h4><p>The last thing to do is to dispatch a custom event when the remove icon is clicked. For this, we need to listen to the remove icon’s click event. The most convenient way is to use the lit-html “<em>@event</em>” notation declaratively, in the element’s template. Let’s add an event listener to the remove icon’s click event:</p><pre>/// part of render function in keyword-tag.ts</pre><pre>render () {<br>   <strong>return</strong> html`<br>      ...<br>      &lt;<strong>span</strong><br>         class=&quot;remove-icon&quot;<br>         @click=&quot;${this.handleRemoveIconClick}&quot;<br>      &gt;<br>      ...<br>   `;<br>}</pre><p>Let’s implement the event handler. When the remove icon is clicked, our component needs to dispatch a custom event with the <strong>keyword</strong> in it, so the parent knows which keyword to remove from the list.</p><pre>/// part of keyword-tag.ts</pre><pre>handleRemoveIconClick() {<br>   <strong>const</strong> event = <strong>new</strong> CustomEvent(&#39;remove-clicked&#39;, {<br>      detail: {<br>         keyword: this.keyword<br>      }<br>   });</pre><pre><strong>   this</strong>.dispatchEvent(event);<br>}</pre><p>Now we can listen to our component’s custom remove-clicked event. Read more about handling events fired by LitElement based components <a href="https://lit-element.polymer-project.org/guide/events#handle-fired-event">here</a>.</p><h3>Using the Component</h3><p>We’re done with implementing our simple component. 😎 The new custom element can be used by other web components or any HTML page. Let’s import the component file in <strong>index.ts</strong>:</p><pre>/// index.ts</pre><pre>import &quot;./keyword-tag&quot;;</pre><p>And finally, use it in <strong>index.html</strong>:</p><pre>/// part of index.html</pre><pre>&lt;<strong>body</strong>&gt;<br>   &lt;<strong>h1</strong>&gt;LitElement Keyword Tag 🔥&lt;/<strong>h1</strong>&gt;<br>   &lt;<strong>keyword-tag</strong> keyword=&quot;litelement&quot;&gt;&lt;/<strong>keyword-tag</strong>&gt;<br>&lt;/<strong>body</strong>&gt;</pre><p>The page should display our web component. 😊</p><h3>Next Steps</h3><p>As homework, you can go ahead and quickly implement a simple <strong>&lt;keyword-set&gt;</strong> LitElement component that takes an array of keywords, and renders it as a list of <strong>&lt;keyword-tag&gt;</strong> elements. Listen to the tags’ <strong>remove-clicked</strong> events to remove them from the list. <a href="https://lit-keyword-panel.stackblitz.io/">See a working example here.</a></p><p>Let me know how it goes! 🔥 🤓</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=599fa5ca6e67" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>