Created
April 29, 2018 17:31
-
-
Save stackdumper/178cd62d3e2ba92692f6a2cb50c75163 to your computer and use it in GitHub Desktop.
react-coolkeys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
import Mousetrap from 'mousetrap' | |
const KeymapContext = React.createContext() | |
export const CoolKeysProvider = ({ keymap, children }) => ( | |
<KeymapContext.Provider value={keymap}>{children}</KeymapContext.Provider> | |
) | |
export const CoolKeys = ({ keymap, children, ...props }) => ( | |
<KeymapContext.Consumer> | |
{(keymap) => ( | |
<CoolKeysBinder keymap={keymap} {...props}> | |
{children} | |
</CoolKeysBinder> | |
)} | |
</KeymapContext.Consumer> | |
) | |
class CoolKeysBinder extends Component { | |
componentDidMount() { | |
const { handlers = {}, keymap = {} } = this.props | |
Object.keys(handlers).forEach((key) => { | |
Mousetrap.bind(keymap[key], handlers[key]) | |
}) | |
} | |
componentWillUnmount() { | |
const { handlers, keymap } = this.props | |
Object.keys(handlers).forEach((key) => { | |
Mousetrap.unbind(keymap[key], handlers[key]) | |
}) | |
} | |
render() { | |
return this.props.children | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment