LitElement equivalent of React "key" concept
Asked Answered
G

1

6
<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>
Geraldina answered 5/2, 2020 at 10:23 Comment(0)
F
6

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';
Felipafelipe answered 5/2, 2020 at 19:12 Comment(2)
I'm not sure how this is related to the questionNakasuji
The key function identifies which index belongs to what render. This way it can behave as requestedGeraldina

© 2022 - 2024 — McMap. All rights reserved.