Magento, Magento 2

How to Use Mixins in Magento 2

How to Use Mixins in Magento 2

In this tutorial, Today I will explain to you what is mixins and how to use mixins in Magento 2. In Backend, When we need to extend functionality or modify some data we’re managed by before, after or around the plugin.

But, In JavaScript, If we need to modify data without override JavaScript file then, how to do? Is It possible?

The answer is Yes. It’s possible by Mixins. But, many people have a question that how to use mixins and implement them in our module?

Let’s follow the steps to create a simple example of mixins. Let’s assume that you have created a module.

You may also like this :

1) First of all, Create requirejs-config.js at app/code/RH/Helloworld/view/frontend/ and paste the below code :

/**
 * Created By : Rohan Hapani
 */

var config = {
    config: {
        mixins: {
            'Magento_Swatches/js/swatch-renderer': {
                'RH_Helloworld/js/swatch-renderer-mixin': true
            }
        } // this is how js mixin is defined
    }
};

Here, I extend Magento_Swatches/js/swatch-renderer this js with our custom js RH_Helloworld/js/swatch-renderer-mixin.

2) Then, Create swatch-renderer-mixin.js at app/code/RH/Helloworld/view/frontend/web/js/ to extend the original function :

/**
 * Created By : Rohan Hapani
 */
define(['jquery'], function ($) {
    'use strict';
    return function (SwatchRenderer) {
        $.widget('mage.SwatchRenderer', SwatchRenderer, {
            _init: function () {
                console.log('Custom Swatch Renderer init function call successfully'); // you can write here your code according to your requirement this._super();
                return this._super();
            }
        });
        return $.mage.SwatchRenderer; // Return flow of original action.
    };
});

That’s it.

Now, you need to remove static content and deploy again static content.

I hope this blog will helpful for easily understand how to use mixins in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Tagged , ,