Back to Lit

03

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

latest2.5 KB
Original Source

The current implementation can be greatly improved:

  • There is an unnecessary input property, dateStr, that accepts a string.
  • The code around willUpdate is a bit messy and imperative.
  • If the user sets date to a new date, the dateStr will not be updated.

The root cause of these issues is that Lit does not have a default converter that converts a string to a Date object. This is where custom attribute converters come in! A custom attribute converter can clean up the implementation of date-display by providing a means to convert a string attribute to a Date object property.

In this step, you'll define a custom attribute converter that can convert a date-string attribute into a Javascript Date object property and back again.

Defining the custom attribute converter

You'll notice a new, empty file called <code>date-converter.<ts-js></ts-js></code> in the editor panel. Use it to define a function that returns a converter.

  • Export a function called dateConverter.
    • The function should receive a locale string as an argument.
  • dateConverter should return a JavaScript Object with the following methods:
    • toAttribute: a function that takes a Date and returns a string.
    • fromAttribute: a function that takes a string and returns a Date.

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

{% switchable-sample %}

ts
import type {ComplexAttributeConverter} from 'lit';

export const dateConverter = (locale: string): ComplexAttributeConverter<Date> => {
  return {
    toAttribute: (date: Date) => {
      return date.toLocaleDateString(locale);
    },
    fromAttribute: (value: string) => {
      return new Date(value);
    }
  }
};
js
export const dateConverter = (locale) => {
  return {
    toAttribute: (date) => {
      return date.toLocaleDateString(locale);
    },
    fromAttribute: (value) => {
      return new Date(value);
    },
  };
};

{% endswitchable-sample %}

{% aside "positive" %}

Simple attribute converters.

If your toAttribute is just toString, then you can use a simple attribute converter instead of a complex attribute converter.

A simple attribute converter is a function that is equivalent to the fromAttribue method of a complex attribute converter object.

{% endaside %}

Congratulations! You've just defined a custom attribute converter! For more information, see Providing a custom converter.

In the next step, you'll put that shiny new converter to work.