Practice creating your custom Tabris.js component

Tabris.js offers a number of built-in components, which allow developers to construct the UI for their native mobile applications. In some cases, you may feel the need for a reusable, custom look and feel component such as the following button with several states:

The custom button above has four states: action, progress, success, and error. Each state represents a different view with relevant styles. When we update the state of the button, relevant views are moved up or down with an animation.

There are several ways to create custom components, but one of the easiest methods is to combine simple built-in widgets into the container you prefer. First, let’s start with the following snippet that shows how the suggested class structure of a custom component looks like in general:

The CustomButton class above has the following characteristics:

  • Extends from Composite Container.
  • Defines events by using @event decorator of tabris-decorators.
  • Defines properties by using @property decorator of tabris-decorators.
  • Accepts property values in the constructor as well.
  • Creates relevant widgets in the constructor.

The structure is a recommendation only, and you are welcome to update it for your own use case.

Now it is time to improve the above class in order to get the operational custom button with different states:

As you can see, the updated class uses the additional features and sources, which we will briefly mention below:

  • The updated class contains the @component decorator at the top of the class declaration in order to use the @getById for direct child access.
  • Defines state accessor property that executes the function updateStateViews when we set a value on it:

    This is a different approach than @property and is useful when you are trying to perform some operations during a variable set or get.
  • Passes some property updates to the super call, which is not expected to be updated anymore.
  • Uses the additional custom component StateView in UI creation. It is convenient to create a custom component (view) and reuse it for repeating groups of views. Here is the source of the custom StateView:

The only unmentioned feature is the @bind decorator in the StateView component, which creates two-way bindings between relevant widgets.

Now, we can use the custom button and update its state as shown in the following sample snippet:

That is all. Hopefully, this blog post encourages more people to create their own custom components. If you have a question or recommendation, feel free to leave a comment below.

You can download the complete project from GitHub.