Search code examples
javascriptreactjsimportmobxmousetrap

Importing Mousetrap in React project - Cannot read property 'bind' of undefined


I'm trying to import mousetrap into a react project for some simple keyboard bindings. I installed Mousetrap via yarn. I don't have any errors importing, but the Mousetrap library object is undefined when I try to use it. This is from my main App.tsx component

import Mousetrap from 'Mousetrap';

export default class App extends React.Component {
componentDidMount() {
    Mousetrap.bind(['left'], dataStore.pagination.prev());
    Mousetrap.bind(['right'], dataStore.pagination.next());
}

componenentDidUnmount() {
    Mousetrap.unbind('left', dataStore.pagination.prev());
    Mousetrap.unbind(['right'], dataStore.pagination.next());
}

public render() {

Here's the error I'm getting. error

I also tried initiating an Mousetrap object to use, but I get this error (plus there's nothing in the documentation saying I would need to).

const mousetrap: Mousetrap = new Mousetrap();

error

I'm using react, typescript, mobx, material-ui and several other libraries, and I'm quite new to all of them. Any advice would be helpful.


Solution

  • Mousetrap has no named export, so your named import statement will result in undefined. You can import the library using:

    import * as Mousetrap from 'Mousetrap';