Vaadin Custom Component Built With Web Components in Java
Write a custom Vaadin Flow component: compose existing components, or wrap a web component with Tag, JsModule, properties, events and server calls.

Vaadin Flow ships a large set of components, and sooner or later you need one it lacks: a rating widget, a map, a third-party chart. Flow lets you build that component two ways, by composing existing ones in Java or by wrapping a web component, and both end up as a class you use like any built-in. This post is for Vaadin 25. It starts with composition because it is cheaper, then wraps a custom element with properties and events, and ends with the build and styling traps. The server model behind all of it is in how Flow works.
Compose first
If the new thing is a combination of components that already exist, do not touch JavaScript.
class EmailField extends Composite<HorizontalLayout> {
private final TextField local = new TextField();
private final Select<String> domain = new Select<>();
EmailField() {
domain.setItems("example.com", "javahacks.dev");
getContent().add(local, new Span("@"), domain);
}
String getValue() {
return local.getValue() + "@" + domain.getValue();
}
}Composite<T> wraps a root component and hides it. Users of EmailField see only the methods you chose to expose, not the layout inside, so you can change the internals without breaking them. It is the lowest-cost kind of reuse, and a surprising share of "we need a custom component" turns out to be this.
Wrap a web component
Suppose a rating-stars custom element exists, with a value property and a rating-changed event. Put its script in the frontend folder, src/main/frontend/rating-stars.js:
class RatingStars extends HTMLElement {
set value(v) { this._value = v; this.render(); }
get value() { return this._value || 0; }
render() {
this.textContent = '★'.repeat(this.value) + '☆'.repeat(5 - this.value);
}
connectedCallback() {
this.addEventListener('click', () => {
this.value = (this.value % 5) + 1;
this.dispatchEvent(new CustomEvent('rating-changed',
{ detail: { value: this.value } }));
});
}
}
customElements.define('rating-stars', RatingStars);Then the Java side:
@Tag("rating-stars")
@JsModule("./rating-stars.js")
public class RatingStars extends Component {
public void setValue(int value) {
getElement().setProperty("value", value);
}
public int getValue() {
return getElement().getProperty("value", 0);
}
public Registration addRatingListener(ComponentEventListener<RatingEvent> listener) {
return addListener(RatingEvent.class, listener);
}
@DomEvent("rating-changed")
public static class RatingEvent extends ComponentEvent<RatingStars> {
private final int value;
public RatingEvent(RatingStars source, boolean fromClient,
@EventData("event.detail.value") int value) {
super(source, fromClient);
this.value = value;
}
public int getValue() {
return value;
}
}
}Each annotation does one job. @Tag names the element Flow creates in the browser. @JsModule tells the build to include the script, so the custom element is defined before Flow uses it. setProperty pushes a value from the server to the browser, and the matching getter reads it back. @DomEvent turns a browser event into a Java event, and @EventData names exactly which fields of the event travel to the server, so a click sends one number, not the whole event object. That choice matters on slow connections, because every event is a network round trip.
Calling into the client
getElement().callJsFunction("focus");
getElement().executeJs("this.value = $0", 3);callJsFunction calls a method on the element, and executeJs runs a snippet where this is the element and $0 is a parameter. Use both sparingly. A component with a clear property and event API is easy to test and to reason about. One that is driven by script strings scattered through the codebase is not, and refactoring tools cannot see inside the strings.
Third-party packages
Install a package from npm and import it inside a JavaScript module, or declare it from Java:
@NpmPackage(value = "@lit/reactive-element", version = "2.0.4")Pin versions. The production bundle includes everything you import, so an unpinned package can change the size and behavior of the build between two runs. The build and deploy steps are described in the production build. A missing import is the classic cause of an application that works in development and shows a blank page after the production build, so open the browser console first when that happens.
Styling a component with a shadow root
A web component with a shadow DOM does not take styles from the page. It exposes CSS custom properties and ::part selectors, and only those can be targeted from outside. That decision belongs in the element's design: if it exposes no parts, nobody can restyle it later without editing it. Vaadin's own components follow this pattern, and the application theme is where your overrides go, as described in theming.
Making the wrapper feel native
Built-in Vaadin components share conventions, and a wrapper that follows them is easier for the next developer. Implement HasSize and HasStyle so callers can call setWidth and addClassName. Implement HasValue if the component holds a value the user edits, which also lets it work with data binding and forms, so a Binder can bind it like a TextField. Name events addXListener, return a Registration so a listener can be removed, and keep the component free of state that is not in an element property, because Flow can recreate the browser side after a reconnect and anything held only in JavaScript is lost.
Read-only and disabled states deserve a thought too. Flow sets the disabled attribute on a disabled component, and a custom element has to respect it by ignoring clicks. Forgetting that is the usual accessibility defect in wrappers, and it is easy to test by calling setEnabled(false) and clicking.
Test the Java side without a browser
The wrapper is plain Java, so a unit test can create the component, call setValue(3), and assert on getElement().getProperty("value"). To check events, fire the DOM event programmatically using ComponentUtil.fireEvent with a RatingEvent, and assert that your listener ran. Browser-level behavior, such as the click handler in the script, needs a browser test, so keep that script small enough that its behavior is obvious and its tests are few.
Accessibility and keyboard use
A custom element has no built-in semantics, so give it some. Set a role and an aria-label from the Java side with getElement().setAttribute("aria-label", ...), make it focusable with a tabindex, and handle the keyboard in the script: arrow keys to change the rating, not only a mouse click. Test it once with the keyboard alone and once with a screen reader. A widget that only responds to the mouse excludes users, and in many organizations it fails a procurement requirement.
Package a component so other projects can use it
A component that two applications need should live in its own Maven module, so that each application depends on it like any other library. The JavaScript and styles go under a resources folder that the Vaadin build picks up:
rating-stars/
pom.xml
src/main/java/dev/javahacks/ui/RatingStars.java
src/main/resources/META-INF/resources/frontend/rating-stars.js
src/main/resources/META-INF/resources/frontend/rating-stars-styles.css@Tag("rating-stars")
@JsModule("./rating-stars.js")
@NpmPackage(value = "lit", version = "3.2.0")
public class RatingStars extends Component implements HasSize {
public RatingStars() {
getElement().setProperty("max", 5);
}
public void setValue(int value) {
getElement().setProperty("value", value);
}
public Registration addValueChangeListener(ComponentEventListener<ValueChangeEvent> listener) {
return addListener(ValueChangeEvent.class, listener);
}
@DomEvent("value-changed")
public static class ValueChangeEvent extends ComponentEvent<RatingStars> {
public ValueChangeEvent(RatingStars source, boolean fromClient) {
super(source, fromClient);
}
}
}Publish the module to your internal repository, add the dependency to the application, and the production build bundles the file with the rest of the frontend. State the supported Vaadin version in the module's documentation, because a component that wraps client code is tied to the frontend toolchain of the release it was built against. Check the version of the npm package you pin against your own, since the example number is illustrative.
When a Java component is the wrong move
If most of the interface is client-side logic, with drag and drop, animation or heavy local state, writing it as a server-driven Flow component fights the model. Hilla with React keeps that logic in the browser and calls typed endpoints on the server, as described in Hilla. For a single widget in an otherwise server-side application, the wrapper above is the right size. The reference is Creating Components, and Web Components on MDN describes the browser standard the wrapper rests on.


