Reusing JBStrap components

Creating custom components using existing components

The next step is to create a new component using previously created or built-in components. Use this solution if you want to separate a set of complex components or if you want to use components in multiple places. Your application's source code becomes more transparent. This might be the case, if you want to create an editable list that appears as a list on the interface but switches to a form while you are editing the data. The user can edit the data in the form, then, if saved, the list (or a card component displaying data) will appear again.

Such components are usually based on some kind of container component. In most cases, this container component is the Div component, which has no event handling and is not visible on the interface and it only collects components. If your custom component needs event handling, one or more of the interfaces listed in the previous section must be placed into the created component, thus enabling event handling.

Implementation

In this example, we will create a card component that displays user data. The component will handle click, mouse, and drag and drop events. The card component must be given a user ID used to query the required data from the database and display the card on the interface. It will also display the user's picture, name, email address, and user name.

The component will extend the Div container component, which will be provided with the events mentioned above. When creating a component, build its structure and also assign an invisible component to it. If the user data is not available, this text will appear on the card instead of the user data.

Source code of a card component:

We created the card component with the above code, now let's see how to place it on a page:

Placing the UserCard component on a page:

The above source code displays 10 cards on the interface with user data with a unique ID between 1-10. In addition, a click event handler has been added to each UserCard component, which causes the application to navigate to the corresponding user data editing page when the user clicks on one of the card components.