Create the most basic UI Component
In this lesson, we will create the most basic UI Component possible. A UI Component is considered a JavaScript component and uses RequireJS’s define
method to return an object.
Setting Up the Directory and File
- In the web folder of your module, create a new directory named
js
. - Inside the
js
directory, create a new JavaScript file namedfree-shipping-banner.js
.
Writing the UI Component
- Start by typing
define
in yourfree-shipping-banner.js
file. - The first argument is an array of dependencies. The only dependency in this file will be
uiComponent
. Make sure to use the correct casing, otherwise it won’t be imported properly. - The second argument is a function callback with the first parameter being
Component
. This is a common convention in the core code. - Inside the function callback, use strict mode, which is common for all JavaScript files written in Magento.
- Finally, return the
Component
.
This is the most basic UI Component possible. We are just returning an instance of Component
, but by definition, this is a standard UI Component.
Making Magento Aware of the UI Component
UI Components are typically passed in as an argument to a block. Follow these steps to make Magento aware of your UI Component:
- Go back to your
default.xml
file and open up the block tag. - Inside the block tag, create a new node called
arguments
. - For the argument name, pass in
jsLayout
and set thexsi:type
toarray
. - Within the
arguments
node, create a new item node with the namecomponents
and set thexsi:type
toarray
. - Within the
components
node, pass in a new item with the namefree-shipping-banner
. This is an arbitrary name, but it’s a good idea to keep it the same as the UI Component. Set thexsi:type
toarray
. - Inside the
free-shipping-banner
node, reference your UI Component with the namecomponent
and anxsi:type
ofstring
. - The value of this item node will be a reference to your UI Component. Start with your namespace name, followed by your module name, and then
/js/free-shipping-banner
.
Passing the UI Component to the Block
- Open your block file, which is defined in your
free-shipping-banner.phtml
file. - Within this file, create a new script tag with a
type
oftext/x-magento-init
. - Inside the script tag, create a JSON object with a key of
#free-shipping-banner
. This is a selector that references the element you want to bind to. - The value for this property will be another JavaScript object. Call
Magento_Ui/js/core/app
, which is responsible for initializing UI Components. - Pass the value of an echo out with PHP and call the
block->getJsLayout()
function.
We have created a basic UI Component, made Magento aware of it, and passed it to our block. If you refresh your site, you should see the output logged to the console, indicating that your UI Component has been instantiated correctly and is loading on the page.
Enroll to access all lessons, source code & comments.
Enroll now to Unlock