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:


Alternative Formats
This post is also available in Markdown: View source