Back to Lit

03

packages/lit-dev-content/site/tutorials/content/word-viewer/03.md

latest1.4 KB
Original Source

By the end of this step, you'll render one single word from the words property, based on some internal reactive state in our component.

Internal reactive state refers to reactive properties that are not part of the component's public API, therefore don't have an associated attribute.

Define idx, an internal state property that will track which word is shown.

{% switchable-sample %}

ts
// word-viewer.ts
class WordViewer extends LitElement {
  @state() private idx = 0;
  ...
}
js
// word-viewer.js
  static properties = {
    idx: {state: true},
    ...
  };

  constructor() {
    ...
    this.idx = 0;
  }

{% endswitchable-sample %}

Then in the render method split the words by the '.' separator, and show the word at the array index of idx % splitWords.length. The % operator will keep the resulting index in the bounds of the splitWords array.

{% switchable-sample %}

ts
// word-viewer.ts

  render() {
    const splitWords = this.words.split('.');
    const word = splitWords[this.idx % splitWords.length];
    return html`<pre>${word}</pre>`;
  }

js
// word-viewer.js

  render() {
    const splitWords = this.words.split('.');
    const word = splitWords[this.idx % splitWords.length];
    return html`<pre>${word}</pre>`;
  }

{% endswitchable-sample %}

The preview should show 👋.