Documentation

Documentation versions (currently viewingVaadin 24)

Creating an In-Project Web Component

How to create an UI component specific to an application.

In the majority of circumstances, the best way to integrate a public Web Component into Vaadin is to follow the steps in Integrating a Web component.

As an alternative, if you want to create a UI component that’s specific to your application, you can integrate and develop the component within your application project.

This section demonstrates how to do this using the https://start.vaadin.com.

Creating the Component Template

The first step is to create the JavaScript Lit template in frontend/my-test-element/my-test-element.js

Example: Defining the my-test-element JavaScript template.

import { html, LitElement } from 'lit';

class MyTestElement extends LitElement {

  static get properties() {
    return {
      name: { type: String }
    }
  }

  render() {
    return html`
      <h2>Hello ${this.name}</h2>
    `;
  }
}

window.customElements.define('my-test-element', MyTestElement);

Creating the Component Java API

This works in exactly the same way as described in Creating Java API for a Web Component, except that the static files are loaded from your project. You can modify them while creating the Java API.

Example: Defining the matching template class.

@Tag("my-test-element")
@JsModule("my-test-element/my-test-element.js")
public class MyTest extends Component {

    public MyTest(String msg) {
        getElement().setProperty("name", msg);
    }
}

Using the Web Component

You can now use the component in other parts of your code.

Example: Using the component in the MainView class.

public class MainView extends VerticalLayout {
    public MainView() {
        add(new MyTest("World"));
    }
}

F3B26182-6375-44E5-8B83-09BE00801C2A