Using Knockout in Magento 2

Reading Time: 2 minutes

Many people who are new to Magento and have read about Knockout JS before will think this is just confined to the new checkout page (and this is where Knockout JS is mainly used in M2). In reality, Knockout JS can be used anywhere within the front-end to create anything from a custom color picker to your own custom image viewer.

Now we know how Knockout JS can be used within Magento 2, so let’s jump into a quick example of how to set up a basic component.

Creating a component

In this example, we’ll be defining a component outside the checkout. There are five steps to get a working component:

1.- Create a new phtml template file

Create a new block template file (phtml) in your module of choice (our example will use the Magento_Catalog module):


2.- Create an XML


<?xml version="1.0"?>
<page xmlns:xsi=""  xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
      <referenceContainer name="content">
        <block class="Magento\Framework\View\Element\Template" name="new.ko.component" template="Magento_Catalog::newko-component.phtml" before="category.products" />

3.- Define Knockout in phtml

<div id="m2-component" data-bind="scope:'m2kocomponent'">
    <!-- ko template: getTemplate() --><!-- /ko -->
    <script type="text/x-magento-init">
        "#m2-component": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "m2kocomponent": {
                        "component": "Magento_Catalog/js/m2kocomponent",
                        "template" : "Magento_Catalog/m2kocomponent-template"

4.- Create a component file


define(['jquery', 'uiComponent', 'ko'], function ($, Component, ko) {
        'use strict';
        return Component.extend({
            initialize: function () {

5.- Create an html template file


<div class="component-wrapper">
    <div data-bind="text: 'Catalog Timer'"></div>

Clear your Magento 2 cache. If everything worked out, you should see some text at the top of your category page, saying 'Catalog Filter'.

Now that we have a working component setup we can start taking a look at how powerful KO JS is within the context of Magento 2, at this point, we have a UI component that we can manipulate through Knockout.

If you want to know about MagmaLabs, visit us here!

Thanks to Juan Carlos Gil, the author of this cool blog post!

You May Also Like
Read More

3 ecommerce platforms for retailers

Reading Time: 2 minutes Non-store retailing continues strengthening worldwide, and according to Euromonitor analyst, Amanda Bourlier, in 2021 sales for more than…