Create a component
In this step, you’ll fill in the gaps in the starting code to create an element class with a basic HTML template.
Starting code
my-element.js
/**
* TODO: Import the LitElement base class and html helper function.
*/
import { } from '';
/**
* TODO: Create a class for your element that extends the LitElement
* base class.
*/
class MyElement { }
/**
* TODO: Register the new element with the browser.
*/
customElements.define();
Click Launch Code Editor to edit the starting code. When you’re ready to see your code in action, click Preview.
-
Import the
LitElement
base class andhtml
helper function.In my-element.js, replace the existing
import
statement with the following code:import { LitElement, html } from 'lit-element';
-
Create a class for your element that extends the LitElement base class.
In my-element.js, replace the existing class definition with the following code:
class MyElement extends LitElement { render() { return html` <p>Hello world! From my-element</p> `; } }
The
render
function defines your component’s template. You must implementrender
for every LitElement component. -
Register the new element with the browser.
In my-element.js, replace the existing call to
customElements.define()
with the following code:customElements.define('my-element', MyElement);
Here’s the completed code for this step:
my-element.js
import { LitElement, html } from 'lit-element';
class MyElement extends LitElement {
render() {
return html`
<p>Hello world! From my-element</p>
`;
}
}
customElements.define('my-element', MyElement);
Your code sample should be working now. LitElement components are added to a page with simple HTML tags, like this:
<my-element></my-element>