Search code examples
lit-elementlit-html

LitElement equivalent of React "key" concept


<example name="One"></example>
<example name="Two"></example>
<example name="Three"></example>

Next render looks like this:

<example name="Four"></example>
<example name="Three"></example>

LitElement will remove the last element and update the first two with new properties.

How do I change this so that LitElement removes all elements except name="three" and a new element is created with name="Four" on first position?

Using React, this would be accomplished by giving them a key property. I want to achieve the same result using LitElement.

<example key="1" name="One"></example>
<example key="2" name="Two"></example>
<example key="3" name="Three"></example>

Solution

  • For this you want to use the lit-html repeat directive. From the docs:

    The repeat directive performs efficient updates of lists based on user-supplied keys:

    repeat(items, keyFunction, itemTemplate)

    Where:

    • items is an Array or iterable.
    • keyFunction is a function that takes a single item as an argument and returns a guaranteed unique key for that item.
    • itemTemplate is a template function that takes the item and its current index as arguments, and returns a TemplateResult.

    For example:

    const employeeList = (employees) => html`
      <ul>
        ${repeat(employees, (employee) => employee.id, (employee, index) => html`
          <li>${index}: ${employee.familyName}, ${employee.givenName}</li>
        `)}
      </ul>
    `;
    

    If you re-sort the employees array, the repeat directive reorders the existing DOM nodes.

    To use repeat you'll need to import it from lit-html:

    import {repeat} from 'lit-html/directives/repeat';