Skip to content

Easily integrate your react component with keyboard arrow keys, with the same configuration used in swipe-react and wheel-react packages.

License

Notifications You must be signed in to change notification settings

leon-good-life/arrow-keys-react

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Arrow Keys React

npm version

NPM

Easily integrate your react component with keyboard arrow keys, with the same configuration used in swipe-react and wheel-react packages.

Usage

  1. Install the npm package:
    npm install --save arrow-keys-react
  1. Import it:
    import ArrowKeysReact from 'arrow-keys-react';
  1. 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.');
      }
    });
  1. 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, add tabIndex 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 to focus() when it loaded.
  • ArrowKeysReact.config can be placed in render function instead of in the constuctor function.

About

Easily integrate your react component with keyboard arrow keys, with the same configuration used in swipe-react and wheel-react packages.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published