DEV Community

The benefits of Web Component Libraries

Thomas Broyer on February 27, 2023

Web component browser APIs aren't that many, and not that hard to grasp (if you don't know about them, have a look at Google's Learn HTML section a...
Collapse
 
vegegoku profile image
Ahmad K. Bawaneh

A read worth the time, excellent and thank you.
How do you see the relation between J2CL and web-components in the future? or should we consider J2CL for business logic only and not for UI logic? do we expect the possibility to be able to optimize web-components?

Collapse
 
tbroyer profile image
Thomas Broyer

I wouldn't use Java to create web components (YMMV). To consume components, generate JsInterop interfaces (maybe even widgets) from a custom element manifest, or a .d.ts.

Collapse
 
vegegoku profile image
Ahmad K. Bawaneh

Makes sense, but I would love to learn about why not?

Thread Thread
 
tbroyer profile image
Thomas Broyer

I don't think there's any web component library that's (directly) usable from J2CL, so you'd first have to make one. It might be possible to use Lit or FAST from J2CL but you'd likely want to first create some tooling to make the calls to tagged templates more readable; e.g. from an interface similar to SafeHtmlTemplate:

interface MyTemplate extends LitHtmlTemplates {
     @Template("<span class=\"{3}\">{0}: <a href=\"{1}\">{2}</a></span>")
     TemplateResult messageWithLink(TemplateResult message, SafeUri url, String linkText, String style);
}
Enter fullscreen mode Exit fullscreen mode

to

static final String[] STRINGS = { "<span class=\"", "\">", ": <a href=\"", "\">", "</a></span>" };
// …
public TemplateResult messageWithLink(TemplateResult message, SafeUri url, String linkText, String style) {
    return Lit.html(STRINGS, style, message, url.asString(), linkText);
}
Enter fullscreen mode Exit fullscreen mode

assuming a definition like:

@JsMethod
public native TemplateResult html(String[] strings, Object... values);
Enter fullscreen mode Exit fullscreen mode

But I don't see much use for J2CL or GWT nowadays (J2CL might be useful for sharing logic with the backend or a native app, the same way Google uses it, but not really for building UI). I mean, even Vaadin is pivoting with Hilla. That's my personal opinion though, and I won't try to push it through anyone's throat. Feel free to disagree, but I'm not interested in arguing about any of it.