Back to Lit

04

packages/lit-dev-content/site/tutorials/content/working-with-lists/04.md

latest2.1 KB
Original Source

Creating a list is also useful for rendering repeated patterns like a game board, for instance.

The range() directive provides a simple way of creating an iterable of incrementing integers which can be used with the map() directive to programmatically render a list of templates in a convenient manner. Nesting this allows you to create multi-dimensional patterns.

The example component already has some styles defined to create an 8 by 8 board to be filled with <div>s whose background color will be determined by adding classes "black" or "white".

Start by importing both directives.

{% switchable-sample %}

ts
// my-element.ts
import {range} from 'lit/directives/range.js';
import {map} from 'lit/directives/map.js';
js
// my-element.js
import {range} from 'lit/directives/range.js';
import {map} from 'lit/directives/map.js';

{% endswitchable-sample %}

Use these directives to create black and white squares like a chess board.

{% switchable-sample %}

ts
// my-element.ts
  render() {
    return html`<div id="board">
        ${map(range(8), (row) => map(range(8), (col) => html`
          <div class="${getColor(row, col)}">${getLabel(row, col)}</div>
        `))}
      </div>
    `;
  }
js
// my-element.js
  render() {
    return html`<div id="board">
        ${map(range(8), (row) => map(range(8), (col) => html`
          <div class="${getColor(row, col)}">${getLabel(row, col)}</div>
        `))}
      </div>
    `;
  }

{% endswitchable-sample %}

This works like a nested for loop for generating a 2 dimensional grid.

The range() directive is used to generate an iterable of integers from 0 to 7 that's passed into the map() directive. For each of the row integers, a range of column integers from 0 to 7 are generated and mapped to result in a <div>. The class names and the text content are derived from the row-column coordinate.

{% aside "info" "no-header" %}

The range() directive's output is customizable by providing additional arguments that control start, end, and the increment step. See the range documentation.

{% endaside %}