🛠 Status: In DevelopmentLitElement is currently in development. It's on the fast track to a 1.0 release, so we encourage you to use it and give us your feedback, but there are things that haven't been finalized yet and you can expect some changes.
LitElement
A simple base class for creating custom elements rendered with lit-html.
LitElement uses lit-html to render into the
element's Shadow DOM
and adds API to help manage element properties and attributes. LitElement reacts to changes in properties
and renders declaratively using lit-html.
-
Setup properties: LitElement supports observable properties that cause the element to update. These properties can be declared in a few ways:
- As class fields with the
@property()decorator, if you're using a compiler that supports them, like TypeScript or Babel. - With a static
propertiesgetter. - By manually writing getters and setters. This can be useful if tasks should
be performed when a property is set, for example validation. Call
invalidateProperty(name, oldValue)in the setter to trigger an update and use any configured property options.
Properties can be given an options argument which is an object that describes how to process the property. This can be done either in the
@property({...})decorator or in the object returned from thepropertiesgetter, e.g.static get properties { return { foo: {...} }.Property options include:
attribute: Describes how and whether the property becomes an observed attribute. If the value isfalse, the property is not added toobservedAttributes. If true or absent, the lowercased property name is observed (e.g.fooBarbecomesfoobar). If a string, the string value is observed (e.gattribute: 'foo-bar').type: Describes how to serialize and deserialize the attribute to/from a property. If this value is a function, it is used to deserialize the attribute value a the property value. If it's an object, it can have keys forfromAttributeandtoAttributewherefromAttributeis the deserialize function andtoAttributeis a serialize function used to set the property to an attribute. If notoAttributefunction is provided andreflectis set totrue, the property value is set directly to the attribute.reflect: Describes if the property should reflect to an attribute. Iftrue, when the property is set, the attribute is set using the attribute name determined according to the rules for theattributepropety option and the value of the property serialized using the rules from thetypeproperty option.shouldInvalidate: Describes if setting a property should trigger invalidation and updating. This function takes thenewValueandoldValueand returnstrueif invalidation should occur. If not present, a strict identity check is used. This is useful if a property should be considered dirty only if some condition is met, like if a key of an object value changes.
- As class fields with the
-
React to changes: LitElement reacts to changes in properties and attributes by asynchronously rendering, ensuring changes are batched. This reduces overhead and maintains consistent state.
-
Declarative rendering LitElement uses
lit-htmlto declaratively describe how an element should render. Thenlit-htmlensures that updates are fast by creating the static DOM once and smartly updating only the parts of the DOM that change. Pass a JavaScript string to thehtmltag function, describing dynamic parts with standard JavaScript template expressions:- static elements:
html`<div>Hi</div>` - expression:
html`<div>${disabled ? 'Off' : 'On'}</div>` - property:
html`<x-foo .bar="${bar}"></x-foo>` - attribute:
html`<div class="${color} special"></div>` - event handler:
html`<button @click="${(e) => this._clickHandler(e)}"></button>`
- static elements:
Getting started
-
The easiest way to try out LitElement is to use one of these online tools:
-
Runs in all supported browsers: StackBlitz, Glitch
-
Runs in browsers with JavaScript Modules: JSFiddle, JSBin, CodePen.
-
-
You can also copy this HTML file into a local file and run it in any browser that supports JavaScript Modules.
-
When you're ready to use LitElement in a project, install it via npm. To run the project in the browser, a module-compatible toolchain is required. We recommend installing the Polymer CLI and using its development server as follows.
-
Add LitElement to your project:
npm i @polymer/lit-element -
Create an element by extending LitElement and calling
customElements.definewith your class (see the examples below). -
Install the Polymer CLI:
npm i -g polymer-cli@next -
Run the development server and open a browser pointing to its URL:
polymer serve
LitElement is published on npm using JavaScript Modules. This means it can take advantage of the standard native JavaScript module loader available in all current major browsers.
However, since LitElement uses npm convention to reference dependencies by name, a light transform to rewrite specifiers to URLs is required to get it to run in the browser. The polymer-cli's development server
polymer serveautomatically handles this transform.Tools like WebPack and Rollup can also be used to serve and/or bundle LitElement.
-
Minimal Example
- Create a class that extends
LitElement. - Use a
@propertydecorator to create a property (or implement a staticpropertiesgetter that returns the element's properties). (which automatically become observed attributes). - Then implement a
render()method and use the element's current properties to return alit-htmltemplate result to render into the element. This is the only method that must be implemented by subclasses.
<script src="node_modules/@webcomponents/webcomponents-bundle.js"></script>
<script type="module">
import {LitElement, html, property} from '@polymer/lit-element';
class MyElement extends LitElement {
@property({type: String})
mood = 'happy';
render() {
return html`<style> .mood { color: green; } </style>
Web Components are <span class="mood">${this.mood}</span>!`;
}
}
customElements.define('my-element', MyElement);
</script>
<my-element mood="happy"></my-element>API Documentation
-
render()(protected): Implement to describe the element's DOM usinglit-html. Ideally, therenderimplementation is a pure function using only the element's current properties to describe the element template. This is the only method that must be implemented by subclasses. Note, sincerender()is called byupdate(), setting properties does not triggerinvalidate(), allowing property values to be computed and validated. -
shouldUpdate(changedProperties)(protected): Implement to control if updating and rendering should occur when property values change orinvalidateis called. ThechangedPropertiesargument is an object with keys for the changed properties pointing to their previous values. By default, this method always returns true, but this can be customized as an optimization to avoid updating work when changes occur, which should not be rendered. -
update()(protected): This method callsrender()and then useslit-htmlin order to render the template DOM. Implement to directly control rendered DOM. Typically this is not needed aslit-htmlcan be used in therendermethod to set properties, attributes, and event listeners. However, it is sometimes useful for calling methods on rendered elements, for example focusing an input:this.shadowRoot.querySelector('input').focus(). ThechangedPropertiesargument is a Map with keys for the changed properties pointing to their previous values. Note, callingsuper.update()is required. Before callingsuper.update(), changes made to properties do not triggerinvalidate(), after callingsuper.update(), changes do triggerinvalidate(). -
firstRendered(): (protected) Called after the element's DOM has been updated the first time. This method can be useful for capturing references to rendered static nodes that must be directly acted upon, for example inupdate(). -
updateComplete: Returns a Promise that resolves when the element has completed updating that resolves to a boolean value that istrueif the element completed the update without triggering another update. This can happen if a property is set inupdate()after the call tosuper.update()for example. This getter can be implemented to await additional state. For example, it is sometimes useful to await a rendered element before fulfilling this promise. To do this, first awaitsuper.updateCompletethen any subsequent state. -
invalidate: Call to request the element to asynchronously update regardless of whether or not any property changes are pending. This should only be called when an element should update based on some state not stored in properties, since setting properties automically callsinvalidate. -
invalidateProperty(name, oldValue)(protected): Triggers an invalidation for a specific property. This is useful when manually implementing a property setter. CallinvalidatePropertyinstead ofinvalidateto ensure that any configured property options are honored. -
createRenderRoot()(protected): Implement to customize where the element's template is rendered by returning an element into which to render. By default this creates a shadowRoot for the element. To render into the element's childNodes, returnthis.
Advanced: Update Lifecycle
- When the element is first connected or a property is set (e.g.
element.foo = 5) and the property'sshouldInvalidate(value, oldValue)returns true. invalidate(): Updates the element after waiting a microtask (at the end of the event loop, before the next paint).shouldUpdate(changedProperties): The update proceeds if this returns true, which it does by default.update(changedProperties): Updates the element. Setting properties inside update is handled specially. Before callingsuper.update(), setting properties will not trigger an update. After callingsuper.update()setting properties will trigger an update.render(): Returns alit-htmlTemplateResult (e.g.html`Hello ${world}`) to render element DOM. Setting properties inrender()does not trigger an update.firstRendered(): Called after the DOM is rendered the first time. Setting properties infirstRendered()does trigger an update.
updateCompletepromise is resolved with a boolean that istrueif the element is not pending another update, and any code awaiting the element'supdateCompletepromise runs and observes the element in the updated state.
Bigger Example
import {LitElement, html, property} from '@polymer/lit-element';
class MyElement extends LitElement {
// Public property API that triggers re-render (synced with attributes)
@property()
foo = 'foo';
@property({type: Number})
whales = 5;
constructor() {
super();
this.addEventListener('click', async (e) => {
this.whales++;
await this.updateComplete;
this.dispatchEvent(new CustomEvent('whales', {detail: {whales: this.whales}}))
});
}
// Render method should return a `TemplateResult` using the provided lit-html `html` tag function
render() {
return html`
<style>
:host {
display: block;
}
:host([hidden]) {
display: none;
}
</style>
<h4>Foo: ${this.foo}</h4>
<div>whales: ${'🐳'.repeat(this.whales)}</div>
<slot></slot>
`;
}
}
customElements.define('my-element', MyElement); <my-element whales="5">hi</my-element>Supported Browsers
The last 2 versions of all modern browsers are supported, including Chrome, Safari, Opera, Firefox, Edge. In addition, Internet Explorer 11 is also supported.