Introduction to bed: Reactive Library based on Standard

The bed is interesting among the front-end JavaScript frameworks for reactive programming. It is quite interesting from developers, but it remains relatively under the radar compared to some other frames. Lit is based on standard components Mozilla Web and prefers the speed and small set of useful functions.

Standard component Mozilla Web Standard

If you want to understand the liter, you need to understand web components. The browser standard supported by all the main browsers, web components provide a way to define user interface components. The idea of web components is to give developers a set of tools in the browser to manage the universal needs of the user interface components. In an ideal world, every framework – responds, VIE or something else – sat on a layer of web components and lent greater consistency to the development of websites.

Lit is a clean, concentrated library that makes it easier for a more comfortable developer experience with the use of web components. It works by creating web components, which is only their own HTML elements. These elements can be in React, for example. Here is a simple assembly of greeting components from the standard:


class SimpleGreeting extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    const name = this.getAttribute('name') || 'World';

    this.shadowRoot.innerHTML = `
       
        p {
          color: navy;
          font-family: sans-serif;
          border: 1px solid lightblue;
          padding: 5px;
          display: inline-block;
        }
       
       

Hello, ${name}!

`; } }

This component issues greeting on the basis of name Property, with simple style components. You want to use it, you can enter the web consoles (F12) and then run:


const defaultGreeting = document.createElement('simple-greeting');
document.body.appendChild(defaultGreeting);

How does the component work and what does it do is quite obvious, although there are some interesting features such as a constructor and shadowRoot. In particular, note that web components allow you to define encapsuled functionality using a standard standard that can be directly in the web console.

Web components with bed

Now let’s look at the same functionality, the binding of the bed.

Provides helpers and functions as LitElement And decorators as customElement Together with html and css Function to streamline the development process:


import { LitElement, html, css } from 'lit';
import { customElement, property } from 'lit/decorators.js';

@customElement('simple-greeting-lit')
export class SimpleGreetingLit extends LitElement {

  @property({ type: String })
  name="World"; // default

  static styles = css`
    p {
      color: blueviolet; 
      font-family: sans-serif;
      border: 2px solid mediumpurple;
      padding: 8px;
      display: inline-block;
    }
    span {
      font-weight: bold;
    }
  `;

  render() {
    return html` 

Hello, ${this.name} ! This is Lit.

`; } }

This code excerpt serves the same purpose as an example of our web components, but you can immediately see that the size and complexity has been reduced. Decorators (aka annotation) starting with @ Let’s declare customElement . name Property in a transformed manner. We also dropped the default constructor and no longer requires inline markings for CSS, thanks css Function (branded template of literary function).

It also allows to use the use of render Method for Returning Templates generated html Function. Contents html The function argument allows you to combine HTML with variable interpolation. It’s similar to JSX and other Templing syntax, but note that we are using ${} PLACE {}and that we use this Fer on the component.

The way to try it is the use of an illuminated online playground. Note that you will need to use on this pitch TS (TypeScript) switch to annotations. (This restriction applies only to the playground; the annotation will work with JavaScript in the assembly.)

Adding reactivity to bed components

Now let’s take another step in reactivity and create lighting name interactive variable. We will add an input that allows us to change the name-permeable binding between the year input Component and name displayed in the template. Keeps them synchronization.

The following code included only meaningful parts that changed:


render() {
    return html`
       

Hello, ${this.name} !

`; } _handleNameInput(event: Event) { const inputElement = event.target as HTMLInputElement; this.name = inputElement.value; }

The functionality here is the same as the previous sample, but now we have input Operation element and function. The input is a standard HTML text. It is also a standard value Property, but is a prefix with an operator Lit. Dot operator binds entry to ${this.name}The magic component that makes the input value reactive to this variable. Dot operator says a lit that you want the Live JavaScript feature for value and not a static value. This ensures that the liter will maintain the input up to date with any program changes.

Tea @input The attribute allows us to point to the service of changes on our way _handleNameInput Function. The function itself uses the standard handling of the house to load the input element value and then assigns it the.name variable. This is the other side of a two -way link. When the user changes the value inside the input, the operator updates this.name. Ensures that anywhere this.name It appears, gaining a new value.

The state of the inner component in bed

Another necessary function common to all reactive libraries is the condition of the internal component. It also simplifies the bed of this aspect of reactive programming. Let’s say, for example, we need a show/hide feature. This would depend on the purely internal value of the Booolean, so there is no need to connect it with a feature that interacts with the parent or any of the external. We can declare a new state variable as follows:


  @state()
  private _showSecretMessage = false;

We will now be available in the user interface. We can use it to switch the visibility of the section:


${this._showSecretMessage
  ? html` 

This is the secret message!

` : '' /* Render nothing if false */ }

It will go to the template as part of render Function. It got used to the expression ( ${} construct) and inside it, Javascript TernĂ¡ operator ? : Syntax). This evaluates the segment by ? If this._showSecretMessage is true or the following part : If it’s false. The net result is that if the value is true, we get a piece of HTML template located at this point to the point of view, and if not, we will not get anything.

And that’s exactly what we want – conditional rendering based on our switch. To actually switch the value, we can add a button:


${this._showSecretMessage
  ? html` 

This is the secret message!

` : '' /* Render nothing if false */ }

This button code uses a variable status to display the Advantor designation. Here is how @click Handler looks:


_toggleSecretMessage() {
    this._showSecretMessage = !this._showSecretMessage;
}

Here we simply replace the value of our status variables and the liter performs a work that is reflected in the view on the basis of our ternary display. Now we have a panel that we can show and hide at will.

Rendering collections in bed

Now let’s look at the bed is the ability to portray the collections. We will first create a list Hobbits As a real estate:


@property({ type: Array })
  hobbits = ("Frodo Baggins", "Samwise Gamgee", "Merry Brandybuck", "Pippin Took");

Instead of the condition, we use the property here, because we are likely to set this value from the parent. We also want to view our Hobbits::


 

The Fellowship's Hobbits:

${this.hobbits && this.hobbits.length > 0 ? html`
    ${this.hobbits.map( (hobbitName) => html`
  • ${hobbitName}
  • ` )}
` : html`

(No hobbits listed in this roster!)

` }

TERNARY CONDITIONAL OPERATOR WE USE TO View the Message if Hobbits Are empty. With our default data, we show a list of the most famous hobbits (all except Bilbo). The main work is done using map Functional operator on this.hobbits variable. This allows us to move through each element and to issue the appropriate LIS-FEM brands via lit html Function.

Using a bed to call API

Now switch from the middle country to Westeros and load some character data from the remote API.

We will first create an internal state Variable for managing the promised load:


@state()
  private _characterDataPromise: Promise ;

Furthermore we implement a constructor The first time we have to do something when loading the component. In this case we load data:


constructor() {
    super();
    this._characterDataPromise = this._fetchCharacterData();
  }

Here we call on _fetchCharacterData Function:


private async _fetchCharacterData() {
  const apiUrl = "https://www.anapioficeandfire.com/api/characters?page=1&pageSize=10";

  try {
    const response = await fetch(apiUrl);

      if (!response.ok) {
        throw new Error(`API request failed with status: ${response.status}`);
      }

      const json: Array  = await response.json();

      if (json && json.length > 0) {
        const characterTemplates = json.map((char) => {
          const displayName = char.name || (char.aliases && char.aliases(0)) || "Unnamed Character";
          return html`
             
  • ${displayName} ${char.culture ? html` - Culture: ${char.culture} ` : ''} ${char.born ? html` , Born: ${char.born} ` : ''}
  • `; }); return html`
      ${characterTemplates}
    `; } else { return html`

    No characters found in these lands!

    `; } } catch (error) { console.error("Failed to fetch Game of Thrones character data:", error); return Promise.resolve(html`

    Could not summon characters: ${error.message}

    `); } }

    The code here is the primary standard JavaScript, the excision we use lit html Return function for each case in our load results. But note that messages _fetchCharacterData The refund promised. In the case of a mistake, it does explicitly, but in all boxes the asynchNC function returns to the promise. Note also that resolve The method is called with states html Functional call.

    We used to save the handle to this promise this._characterDataPromise. The stored handle allows us intelligently to wait for the result of this call in the main component template:

    
    return html`
           

    Characters from the Seven Kingdoms (or thereabouts):

    ${until( this._characterDataPromise, html`

    Sending a raven for news (loading characters...).

    ` )} `;

    We used again until() Function to wait for the end result of the promise. Note that the second argument shows the waiting content.

    Conclusion

    Lit contains a lot of interesting ideas and its popularity is not surprising, especially due to its base in the standard web components. The big question is that it turns on as a system of universal components for many other frames such as React, Svelete and Vue. If so, we enter a brand new phase into our elevator and adoption. In the meantime, however, the bed is a viable consent of its OWS, especially attractive to projects that have a high value for standard compliance.

    The source code can be found in my GITHUB report, where you will find all the examples in this article.

    Leave a Comment