What is a UI Component?
A great place to start is understanding what exactly a UI Component is. To do that, let’s take a step back and start with Magento 2.
Model View ViewModel Architecture
Magento 2 uses a Model View ViewModel (MVVM) architecture, which means it has a great abstraction between the model or data layer, the view or presentation layer, and the conditional logic that could affect the view. This architecture is also known as MVVM.
View Layer Components
The first V in MVVM is the view in Magento, and it is represented by three major components: the layout, blocks, and templates.
- Layout: The layout of the page is created with XML, and this builds the basic structure of a page.
- Blocks: Blocks are then laid out on the page and represent sections on the page within the layout. These pages are rendered from a combination of PHP and HTML.
- Templates: This combination of PHP and HTML represents what we know as a PHTML file.
The layout, blocks, and template sections make up the view layer of Magento. However, these three sections only represent the server-side rendered part of the view layer. There’s also a whole other JavaScript layer rendered by the client.
UI Components
UI Components are similar to React or Vue components in that they represent actual elements on the page. Specifically, they render a fragment of code that represents the user interface or UI. The JavaScript that dynamically renders elements on a page can also talk to servers by calling APIs. This means that UI Components can be a combination of server-side data and client-side rendering.
Reusability and Cascading
Components can also cascade for great reusability in the front end of your app. This cascading effect can simplify your codebase and promote reusing components all across your front end. UI Components make up their entirely own view layer and are made from a combination of server-side and client-side architectures.
Defining UI Components in Layout XML Files
UI Components are initially defined in layout XML files. The output of this XML is translated into JSON. The JSON is then processed and rendered to the browser. The JSON is processed by the browser, which then initializes the bootstrapping process of UI components. This includes instantiating JavaScript to find ViewModels, and then rendering the output in the form of KnockoutJS templates.