What you'll learn
- how to create elements
- how to implement various renderers
This article uses the original
@webiny/ui-composer package to showcase the creation of a completely custom UI element, the same way you would do it in your project.
Elements are the basic building blocks of your UI, and allow you to have a nice, developer-friendly SDK for your projects. In this article we look at how to create a simple element, how to make it pluginable, and how to support various renderers.
Let's create a
HeadingElement element, to render simple heading tags. It will accept
You can structure the class however you like. This is not React, these are plain classes. The only important thing is that it extends the
UIElement base class.
When instantiating an element, it always needs to have a unique ID. That's how other developers will be able to reference that particular element from their plugins.
When you add this element to a view (as described in the Building Views article), it will render an
<h2> element. Currently, this element only supports
h2. We'll expand the rendering capabilities later in the article.
To make your custom elements extendable via plugins, we need to call the plugins from the class constructor. We also need to add some getter/setters so that other developers can modify your element instances. Exposing a public interface is important for other developers to be able to successfully interact with your elements.
Now anyone can hook into your element from the outside, using the
Up to this point, we were using the
render method almost as if it's plain React. If it's your final implementation, and you don't need to have your renderers pluginable, you can do it. The only downside is that external developers will not be able to add new renderers to elements shipped in this manner.
Let's look at how you can improve this element class to support pluginable renderers.
In this example, we'll implement a default renderer, which supports
<h2>, and falls back to
<h2> if it runs into an unsupported heading size.
That's our renderer. Now we can use it in the
HeadingElement class. This is what your element class should look like:
As you can see, we removed the
render method override to let the base
UIElement class do its magic, and we registered a renderer instance in the constructor. Looking in the browser, the output is the same as before. But now we can add more renderers.
Let's add another renderer that will only handle
size: 3 elements: