CHROMABITS

1 minute

Here’s a little mixin I’ve been using on React.js for interacting with the Mousetrap library (a library for handling keyboard shortcuts on the browser). It automatically unbinds shortcuts once the component unmounts and provides some convenience methods for avoiding interacting with Mousetrap directly on m components.

NOTE: The following code is formatted for Browserify. You might need to make some changes for using it without Browserify

To use it, require the module and add the mixing to your component:

// ...
var MoustrapMixin = require('/path/to/MoustrapMixin.jsx');

MyComponent = React.createClass({
    // ...
    mixins: [MoustrapMixin],

    componentDidMount: function () {
        this.bindShortcut('esc', function () { // Handle shortcut });
    }
    // ...
});

MoustrapMixin.jsx:

CHROMABITS
Copyright © 2015-2019 - Eduardo Trujillo
Except where otherwise noted, content on this site is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license.
Site generated using Gatsby.