arrow-keys-react
v1.0.6
Published
Easily integrate your react component with keyboard arrow keys, with the same configuration used in swipe-react and wheel-react packages.
Downloads
10,029
Maintainers
Readme
Arrow Keys React
Easily integrate your react component with keyboard arrow keys, with the same configuration used in swipe-react and wheel-react packages.
Usage
- Install the npm package:
npm install --save arrow-keys-react
- Import it:
import ArrowKeysReact from 'arrow-keys-react';
- Config arrow keys events ('left', 'right', 'up', 'down'), at least one of them, in your component constructor, or in render function:
ArrowKeysReact.config({
left: () => {
console.log('left key detected.');
},
right: () => {
console.log('right key detected.');
},
up: () => {
console.log('up key detected.');
},
down: () => {
console.log('down key detected.');
}
});
- Integrate with your React component:
<YourComponent {...ArrowKeysReact.events} />
Example
import React, { Component } from 'react';
import ArrowKeysReact from 'arrow-keys-react';
class App extends Component {
constructor(props){
super(props);
this.state = {
content: 'Use arrow keys on your keyboard!'
};
ArrowKeysReact.config({
left: () => {
this.setState({
content: 'left key detected.'
});
},
right: () => {
this.setState({
content: 'right key detected.'
});
},
up: () => {
this.setState({
content: 'up key detected.'
});
},
down: () => {
this.setState({
content: 'down key detected.'
});
}
});
}
render() {
return (
<div {...ArrowKeysReact.events} tabIndex="1">
{this.state.content}
</div>
);
}
}
export default App;
Remarks
- When you use
div
, addtabIndex
property. - The element must be on focus in order to detect arrow keys. The arrow keys will be detected when the user will click on the element, or focus it using
tab
key in the keyboard. Alterntively you can program your component tofocus()
when it loaded. ArrowKeysReact.config
can be placed inrender
function instead of in theconstuctor
function.