packages/lit-dev-content/site/tutorials/content/working-with-lists/01.md
Lit supports rendering iterables of items directly in templates, but you often need to render a template that uses the items, rather than the items directly.
Lit provides a built-in map() directive that lets you transform the items in
an iterable. The map() directive works with all kinds of iterables, including
arrays, sets, maps, and even generators. It returns an iterable containing the
result of calling the provided callback function on each item.
In this example, you're given a custom element with a state property named
items, which contains a set of strings.
Render each item in the set as a list item (<li>) containing that string.
Begin by importing the map() directive.
{% switchable-sample %}
// my-element.ts
import {map} from 'lit/directives/map.js';
// my-element.js
import {map} from 'lit/directives/map.js';
{% endswitchable-sample %}
Use the directive in the component's template, providing a callback function
that returns a template wrapping each item with a <li> tag, and place it
inside the <ul> tag.
{% switchable-sample %}
// my-element.ts
render() {
return html`
⋮
<ul>
${map(this.items, (item) => html`<li>${item}</li>`)}
</ul>
`;
}
// my-element.js
render() {
return html`
⋮
<ul>
${map(this.items, (item) => html`<li>${item}</li>`)}
</ul>
`;
}
{% endswitchable-sample %}
{% aside "info" "no-header" %}
The index of the item is also made available to the callback function. Check out the map documentation for details.
{% endaside %}
Extra Credit: Try adding an item number to each list item using the index.