Skip to content

Custom components

Miguel Pérez Colom edited this page Oct 6, 2024 · 4 revisions

At some point you probably want to add custom components to your UI which has been built with Mateu. That custom component will also probably be a micro frontend by itself, issuing rest calls to some api.

You can easily add any custom web component to your Mateu UI. Just need load the js in the frontend side and create a class and add some annotations for instantiating your custom web component in the frontend.

Here you have an example:

@Getter
@Setter
@Caption("Web component")
public class WebComponentForm {

    private ModelViewer modelViewer = new ModelViewer();

}


@Element("model-viewer")
@Data
public class ModelViewer {

  @Attribute private String src = "/myassets/NeilArmstrong.glb";

  @Attribute private String style = "width: 400px; height: 400px;";

  @Attribute("auto-rotate")
  private String autoRotate = "auto-rotate";

  @Attribute("camera-controls")
  private String cameraControls = "camera-controls";

  @On(value = "load") // this will be called when the `load` event is dispatched in the client side
  Message onLoad() {
    return new Message(ResultType.Success, "It happened", "Loaded :)", 5000);
  }

}

When you open the form defined by the class WebComponentForm you will create the following element in the browser:

<model-viewer 
        id="modelViewer" 
        name="modelViewer" 
        src="/myassets/NeilArmstrong.glb" 
        style="width: 400px; height: 400px;" 
        auto-rotate="auto-rotate" 
        camera-controls="camera-controls">
</model-viewer>

Please notice that the model-viewer tag does not mean anything to the web browser, so you must first register the web component. You can do it by adding an annotation to the class you annotated with @MateuUI:

@MateuUI("")
@ExternalScripts("https://ajax.googleapis.com/ajax/libs/model-viewer/3.0.1/model-viewer.min.js")
public class Home {
    
    //...
    
}

Which ends up in the following html which goes to the browser

<!DOCTYPE html>
<html lang="en">
<head>
    ...
  <script type='module' 
          src='https://ajax.googleapis.com/ajax/libs/model-viewer/3.0.1/model-viewer.min.js'>
  </script>
    ...
</head>
<body>
  
    ...
  
</body>
</html>

And the browser will show this:

For the example we are using the model-viewer web component but you can create your own and do any api call from there. A micro frontend, indeed.

Clone this wiki locally