Back to Lit

04

packages/lit-dev-content/site/tutorials/content/custom-attribute-converter/04.md

latest2.1 KB
Original Source

Now that the dateConverter has been defined, clean up the implementation of date-display by using the dateConverter.

Use the converter

  • Import the dateConverter from <code>date-converter.<ts-js></ts-js></code>.
  • Set converter on the date reactive property option to an invocation of dateConverter.
    • Pass the navigator.language string as an argument.
  • Enable attribute conversion for date by removing attribute: false.
  • Enable the property to be reflected back to the attribute by setting reflect: true.

date-display.<ts-js></ts-js>

{% switchable-sample %}

ts
import {dateConverter} from './date-converter.js';

export class DateDisplay extends LitElement {
  ...

  @property({converter: dateConverter(navigator.language), reflect: true})
  date = new Date();
  ...
js
import {dateConverter} from './date-converter.js';

export class DateDisplay extends LitElement {
  static properties = {
    date: {converter: dateConverter(navigator.language), reflect: true},
    dateStr: {type: String, attribute: 'date-str'},
  };
  ...

{% endswitchable-sample %}

Clean up references to dateStr

  • Remove the dateStr property.
  • Delete the willUpdate method. (You no longer need to synchronize dateStr with date.)
  • Update index.html to use the date attribute instead.

date-display.<ts-js></ts-js>

{% switchable-sample %}

ts
export class DateDisplay extends LitElement {
  @property({converter: dateConverter})
  date = new Date();

  render() {
    return html`
      <p>The given date is: ${this.date.toLocaleDateString()}</p>
    `;
  }
}
js
export class DateDisplay extends LitElement {
  static properties = {
    date: {converter: dateConverter},
  };

  constructor() {
    super();
    this.date = new Date();
  }

  render() {
    return html`
      <p>The given date is: ${this.date.toLocaleDateString()}</p>
    `;
  }
}

{% endswitchable-sample %}

index.html

html
<date-display date="05/05/22"></date-display>

Now, the date attribute can be properly converted to a JavaScript Date object!