2.0.0-beta-7 • Published 5 years ago

react-input-trigger v2.0.0-beta-7

Weekly downloads
1,633
License
MIT
Repository
github
Last release
5 years ago

React Input Trigger

npm license downloads size

deps peer-deps

React component for handling character triggers inside any textarea or input field. 🐼

Description

Useful for building applications that need to listen on keyboard triggers in text fields, for example Slack-like emoji suggestions (triggered by typing :) or Github-like user mentions (triggered by typing @). This component is a drop-in solution and can be used with existing input fields / textareas.

v2.x has some significant changes from v1. The v1 documentation can be found here.

Getting Started

Install the package

$ npm install react-input-trigger --save

There are two exports from the package:

import { useInputTriggerHook } from 'react-input-trigger'; // Exports a React hook. (Recommended for React >= 16.8)

import { InputTrigger } from 'react-input-trigger'; // Exports a component to wrap your textarea / input field. (Recommended for React < 16.8 or if you'd prefer a component)

useInputTriggerHook (React Hook)

import useInputTriggerHook from 'react-input-trigger/hook';

const ExampleWithHooks = () => {
  const { triggerState, inputTriggerHandler, endTrigger } = useInputTrigger([
    {
      key: '@',
      id: 'mention',
    },
    {
      key: '/',
      id: 'slash-command',
    },
  ]);

  return (
    <>
      <textarea onKeyDown={inputTriggerHandler} />
      <pre>{triggerState}</pre>
      <button onClick={() => endTrigger}>
        Manually stop trigger
      </button>
    </pre>
  )

Hook Configuration

useInputTrigger(<triggerConfigurations>, <options>);

triggerConfiguration

This parameter expects an array of TriggerConfigurations

options (optional)

The hook can take a set of configuration options

OptionTypeDefault valueDescription
escToCancelbooleanfalseSet this as true if you'd like the trigger to be automatically cancelled if the user presses the Escape key.

eg

useInputTrigger(<triggerConfigurations>, {
  escToCancel: true,
});

Hook Values

The following keys are available on the return value of the Hook.

ValueTypeDefault valueDescription
triggerStatetriggerState or nullnullAn object containing meta data about the trigger that was dispatched in the input field / textarea.
inputTriggerHandlerFunction-Handler to listening on triggers. Pass this to the onKeyDown handler of your input field / text area.
endTriggerFunction-Call this method if you need to manually end (cancel) a trigger.

InputTrigger (React Component)

import InputTrigger from 'react-input-trigger/component';

class Example extends React.Component {
  constructor() {
    super();
    this.state = { trigger: null };
  }
  render() {
    return (
      <div>
        <InputTrigger
          triggers={[
            {
              key: '@',
              id: 'mention',
            },
            {
              key: '/',
              id: 'slash-command',
            },
          ]}
          endTrigger={endHandler => { this.endTrigger = endHandler; }}
          onInputTrigger={trigger => this.setState({ trigger })}
        >
          <textarea />
        </InputTrigger>
        <button onClick={() => this.endTrigger()}>End Trigger Manually</button>
      </div>
    );
  }
}

Props

The following keys are available on the return value of the Hook.

ValueTypeDefault valueDescription
triggersArray of TriggerConfigurations[ { key: '@', id: 'mention' } ]List of triggers the wrapper component should listen for.
onInputTriggerFunction-Function that returns a triggerState when a trigger occurs.
endTriggerFunction-Function that returns a callback that you can store and execute whenever you want to manually end an active trigger

Deep Dive

TriggerConfiguration

A TriggerConfiguration is an object to defines a trigger. React Input Trigger will use this object's definition to listen to keyboard events for triggers.

{
  id: string // a unique identifier for this trigger. Default: Date.now()
  key: string // the event.key value you want to listen on. Use this tool to find out the `event.key` value: https://keycode.info/
  shiftKey: boolean // <Optional> Set this as true if you want the shift key to be pressed for the trigger to fire
  altKey: boolean // <Optional> Set this as true if you want the alt key to be pressed for the trigger to fire
  metaKey: boolean // <Optional> Set this as true if you want the windows key / cmd key to be pressed for the trigger to fire
  ctrlKey: boolean // <Optional> Set this as true if you want the ctrl key to be pressed for the trigger to fire
}

triggerState

The triggerState is an object that is returned when a particular trigger fires. It's value can be one of the following:

// First occurrence of the trigger
{
  id: string // id configured
  hookType: 'start'
  cursor: {
    top: number // css top value for the trigger
    left: number // css left value for the trigger
    height: number // css height value for the cursor
  }
}

// On typing after the trigger has started
{
  id: string // id configured
  hookType: 'typing'
  cursor: {
    top: number // css top value for the trigger
    left: number // css left value for the trigger
    height: number // css height value for the cursor
  }
  text: {
    value: string; // string including the trigger key
    content: string; // string without the trigger key
  };
}

// On cancelling the trigger
{
  id: string // id configured
  hookType: 'cancel'
}

Contributing

Want to fix something, add a new feature or raise an issue? Please read the contributing guide to get started. :smile:

Contributors

Thanks goes to these wonderful people (emoji key):

Abinav Seelan💻 📖Aditi Mohanty💻 📖Adam Goldman💻

This project follows the all-contributors specification. Contributions of any kind welcome!

2.0.0-beta-7

5 years ago

2.0.0-beta-6

5 years ago

2.0.0-beta-5

5 years ago

2.0.0-beta-4

5 years ago

2.0.0-beta-3

5 years ago

2.0.0-beta-2

5 years ago

2.0.0-beta-1

6 years ago

2.0.0-beta-0

6 years ago

1.1.2

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.2-beta-1

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago