Table of contents
1.
Introduction
1.1.
Integrating a JS Module into Vaadin
1.2.
Adding Front-End Files
1.3.
Vaadin Directory Add-on Deployment
1.4.
Creating Other Add-on Types
2.
Java API for a Web Components
2.1.
Setting and Reading Properties
2.2.
Listening to Events
2.3.
Calling Element Functions
2.4.
Define Child Content by Adding Sub-Elements
3.
Creating an In-Project Web Component
3.1.
Establishing the Component Template
3.2.
Developing the Java Component API
3.3.
Making use of the Web Component
4.
Frequently Asked Questions
4.1.
Is Vaadin a JavaScript framework?
4.2.
Vaadin is it scalable?
4.3.
How are the Vaadin components installed? Give an instance.
4.4.
How are add-ons installed?
4.5.
What are the add-ons?
5.
Conclusion
Last Updated: Mar 27, 2024

Integrating Web Components

Author dhananjay
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article we are going to learn how to integrate web components using Vaadin.

Vaadin is a web Framework that is open source and  has built-in support for both Java script and AJAX. By using Google Web Toolkit, you may also incorporate outside functionality onto it. Vaadin saves developers time because it produces rich content in the browser devoid of the use of any markup files.

Integrate Web Components

A group of web standards called web components let you make new HTML tags with unique names. Web Components offer complete encapsulation of styles and markup and are reusable.

Specifications

There are four core standards in the Web Component specification, which can be utilised alone or jointly:

  • Custom Elements:  A group of APIs used to specify the functionality of new HTML elements.
     
  • Shadow DOM:  In order for the Web Component to stay "hidden" and distinct from the rest of the DOM, a collection of APIs known as the "Shadow DOM" is used to offer encapsulation of the element's styling, syntax, and functions.
     
  • ES Modules: JavaScript documents can be used and reused in other JS documents according to the standards set forth by ES Modules.  Allows for the building of modular Web components in accordance with JavaScript application development standards.
     
  • HTML Template: You can enter HTML fragments that are inactive upon page load but that can be instantiated at runtime using the <template> element.

 

Vaadin requires the following to use a Web Component:

  • To load the HTML, JS, and CSS files that the component requires.
     
  • A Java API to set up the component and monitor its events.
     

The client-side files for the Web Component (usually JavaScript module files) are accessible through npm. Vaadin utilises and supports npm, installing and utilising npm packages automatically. Additionally, it provides the browser with static files.

Instead of npm, the pnpm utility is utilised for package management.

Integrating a JS Module into Vaadin

Although you can start from scratch and complete it all manually, using the Vaadin Add-on Starter is the simplest option. The result is:

  • A project with each required dependency;

 

  • An import of the chosen component into npm;

 

  • A Java class for a stub component for your Web Component integration;

 

  • An all-inclusive Maven profile that manages the component's deployment to Vaadin Directory
     

Annotations in the Java component class

  • The name of the HTML element is specified by the @Tag annotation.

 

  • The import of the JavaScript module is specified by the annotations @JSModule and @NpmPackage.

Example

@Tag("mwc-slider")
@NpmPackage(value = "@material/mwc-slider",
            version = "0.18.0")
@JsModule("@material/mwc-slider/mwc-slider.js")
You can also try this code with Online Java Compiler
Run Code

Adding Front-End Files

Your component can need front-end files from the project itself, like more JavaScript modules. In this situation, add them to the src/main/resources/META-INF/frontend directory so that, if you decide to create an add-on for your component, they are packaged in the component JAR.

adding a local JavaScript module using the @JsModule annotation.

@JsModule("./my-local-module.js")
You can also try this code with Online Java Compiler
Run Code

Vaadin Directory Add-on Deployment

When you are happy with the API, you can publish the add-on to the Vaadin Directory to make it available to everyone.

  • Use: to produce an add-on package that is compatible with directories.
     
  • mvn clean install -Pdirectory
     
  • In the destination directory, this generates a ZIP file.

The Vaadin Directory accepts the following add-ons:

1.Visit the directory at https://vaadin.com.
 

2.Register or log in.
 

3.Put the ZIP file online.
 

4.To inform others, describe your add-on in writing:

  • How it functions
     
  • Which web browsers are accepted
     
  • Anything else that might be pertinent
     

5.Make your add-on public.

Creating Other Add-on Types

The Add-on Starter can also be used to develop a variety of add-ons, such as a data provider.

To make a project that can be used for any add-on and is generic:

1.Keep the starting form's default Web Component URL.
 

2.Save the project
 

3.Delete:

  • the annotations @JsModule and @NpmPackage.
     
  • the class for UI components.

Java API for a Web Components

Java API For Web Components

Although there are other ways to connect with a web component, the following are the most common:

  • To specify how an element should act, use its properties.
     
  • To be informed when the user takes an action, pay attention to events on the element.
     
  • To carry out particular actions on the element, such as opening a popup, call one of its functions.
     
  • Sub-elements can be added to define child content.

Setting and Reading Properties

The characteristics that an element supports are often listed in its npm JavaScript documentation. Check out the docs, for instance. When the slider thumb is pressed, the paper-pin slider's boolean property determines whether or not a numeric-value label appears.

Any property can have getters and setters added to it, creating a matching Java setter-getter API.

As an illustration, the PaperSlider class's pin property might have a setter and getter added.

public void setPin(boolean pin) {
    getElement().setProperty("pin", pin);
}
public boolean isPin() {
    return getElement().getProperty("pin", false);
}
You can also try this code with Online Java Compiler
Run Code
  • The setter changes the value of the specified property.

 

  • If the property has not been set, the getter returns false as the default value in place of the property's value. The default setting ought to be the same as the Web Component property's default setting.

Listening to Events

Every web element that a user clicks on triggers a click event. You can extend ComponentEvent and use the @DomEvent and @EventData annotations to enable the user of your component to listen to the click event.

As an illustration, consider how the ClickEvent class extends ComponentEvent and makes use of the @DomEvent and @EventData annotations.

@DomEvent("click")
public class ClickEvent extends ComponentEvent<PaperSlider> {
    private int x, y;
    public ClickEvent(PaperSlider source,
                      boolean fromClient,
                      @EventData("event.offsetX") int x,
                      @EventData("event.offsetY") int y) {
        super(source, fromClient);
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}
You can also try this code with Online Java Compiler
Run Code
  • To specify the name of the DOM event to listen for, ClickEvent uses the @DomEvent annotation (click in this case).

 

  • It extends ComponentEvent, which has a typed getSource() method, just like all other events fired by a Component and shares that class.

 

  • To obtain the click coordinates from the browser, two additional function Object() { [native code] } options marked with the @EventData annotation are used.
     
  • When an event is processed in the browser, the expression included in each @EventData annotation is tested. It uses the event prefix to access DOM event properties (e.g., event.offsetX) and the element prefix to access DOM element properties.

Calling Element Functions

Many elements have methods in addition to attributes and events, which can be used in a variety of ways. For instance, if a change is made that the Web Component itself is unable to recognise automatically, the refresh() method of vaadin-board is called. You can provide an API by using the callJsFunction() method in Element to call a function on an element.

To call the increment function on the paper-slider element, use the callJsFunction() method of the PaperSlider class.

public void increment() {
    getElement().callJsFunction("increment");
}
You can also try this code with Online Java Compiler
Run Code

Define Child Content by Adding Sub-Elements

Child elements may be included in some web components. Implementing the HasComponents interface should be sufficient if the component is a layout type and you just wish to add child components. For the methods add(Component...), remove(Component...), and removeAll(), this interface offers default implementations.

As an illustration, consider using HasComponents to create your own div> wrapper.

@Tag(Tag.DIV)
public class Div extends Component implements HasComponents {
}
You can also try this code with Online Java Compiler
Run Code

Then, you can use the techniques offered to add and remove components.

Using the add() methods offered by the HasComponents interface, for instance.

Div root = new Div();
root.add(new Span("Hello"));
root.add(new Span("World"));
add(root);
You can also try this code with Online Java Compiler
Run Code

Creating an In-Project Web Component

Creating an In-Project Web Component

As an alternative, you can integrate and develop the component within your application project if you wish to create a UI component that is unique to your application.

Establishing the Component Template

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

Example: defining the JavaScript template for the my-test-element.

import { html, LitElement } from 'lit';
class TestElement extends LitElement {
  render() {
    return html`
      <h2>Coding Ninjas</h2>
    `;
  }
}
window.customElements.define('my-test-element', TestElement);
You can also try this code with Online Javascript Compiler
Run Code

Developing the Java Component API

With the exception of the fact that the static files are loaded from your project, this operates exactly as explained in Java API for Web Components. They are simple to change while developing the Java API.

Creating the appropriate template class, as an example.

@Tag("my-test-element")
@JsModule("my-test-element/my-test-element.js")
public class MyTest extends Component {
    public MyTest(String prop1) {
        getElement().setProperty("prop1", prop1);
    }
}
You can also try this code with Online Java Compiler
Run Code

Making use of the Web Component

The component is now available for use in other sections of your code.

Using the MainView class component as an example.

public class MainView extends VerticalLayout {
    public MainView() {
        add(new MyTest("World"));
    }
}
You can also try this code with Online Java Compiler
Run Code

Frequently Asked Questions

Is Vaadin a JavaScript framework?

An open-source Java framework for creating web applications is called Vaadin Flow. You can create an app entirely using UI elements without ever touching HTML or JavaScript.

Vaadin is it scalable?

Vaadin apps scale effectively. Errors are possible with any framework, as with anything else. However, it's simple to develop applications with Vaadin that not only scale well but also look amazing and operate excellently, making your users happy, by adhering to traditional Java best practices.

How are the Vaadin components installed? Give an instance.

Usually, npm or Bower are used to install the Vaadin components. For instance, the component vaadin-button can be installed with the following command:  bower install vaadin/vaadin-button

How are add-ons installed?

By simply including a Maven or Ivy dependency, downloading the JAR file, and dropping it in the project's web library folder, one can install add-ons from the Vaadin Directory.

What are the add-ons?

Many others are offered as add-ons in addition to the elements, themes, layouts, and data sources integrated into the base Vaadin library.

Conclusion

In this article, we learned what Vaadin is, how to integrate web components in Vaadin using two alternative approaches, and how to construct a Java API to communicate with the component.

To learn more about the Vaadin please refer to the following articles:

Vaadin-Creating First Application

Vaadin-Core Elements

Vaadin-User Interface Components

To learn more about DSA, competitive coding and many more knowledgeable topics, please look into the guided paths on Coding Ninjas Studio. Also, you can enroll in our courses and check out the mock test and problems available to you. Please check out our interview experiences and interview bundle for placement preparations.

thank you

Please upvote our blog to help other ninjas grow.

Happy Learning

Live masterclass