Render Lists

To render a list of items, use for:each directive or the iterator directive to iterate over an array. Add the directive to a nested <template> tag that encloses the HTML elements you want to repeat.

The iterator directive has first and last properties that let you apply special behaviors to the first and last items in an array.

Regardless of which directive you use, you must use a key directive to assign a unique ID to each item. When a list changes, the framework uses the key to rerender only the item that changed. The key in the template is used for performance optimization and isn’t reflected in the DOM at run time.

To follow along in a code editor, open the helloForEach and helloIterator components from the github.com/trailheadapps/lwc-recipes repo. You can also copy the code to the component IDE.

When using the for:each directive, use for:item="currentItem" to access the current item. This example doesn’t use it, but to access the current item’s index, use for:index="index".

To assign a key to the first element in the nested template, use the key={uniqueId} directive.

This example iterates over an array called contacts, which is defined in the component’s JavaScript class.

List of names and titles.

Every item in a list must have a key. When a list changes, the framework uses the key to identify each item so that it can rerender only the item that changed. The key must be a string or a number, it can't be an object. You can’t use index as a value for key. Assign unique keys to an incoming data set. To add new items to a data set, use a private property to track and generate keys.

To apply a special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}. Use the iterator directive on a template tag.

Use iteratorName to access these properties:

  • value—The value of the item in the list. Use this property to access the properties of the array. For example, {iteratorName}.value.{propertyName}.
  • index—The index of the item in the list.
  • first—A boolean value indicating whether this item is the first item in the list.
  • last—A boolean value indicating whether this item is the last item in the list.

This sample code uses the same array as the previous example. To apply special rendering to the first and last items in the list, the code uses the first and last properties with the lwc:if directive.

If the item is first in the list, the <div> tag renders with the styling defined in the CSS list-first class. If the item is last in the list, the <div> tag renders with the styling defined in the CSS list-last class.

List of names and titles with the first name and title rendered in bold.

The wireGetPicklistValues component in the lwc-recipes repo uses the lightning-input base component to display a list of picklist values.

See Also