Search code examples
javascriptreactjsreactjs-flux

How to add special character with shortcut to any input?


I have an app where I need to add a special character, an emoji or something similar, every time the user press a shortcut Ctrl+D.

The problem is I'm using flux and have several inputs on my page, so when someone adds a char into one of the inputs it will call an action, dispatch to the store, and they update the view.

To add this special char I need to handle the keyEvent and know which input component was being used to update the corresponding attribute in the store.

handleShortcut(evt) {
    if (evt.keyCode === ...) {
        MyActions.addSpecialChar();
        evt.preventDefault();
    }
}

Is this the only way? I know that I can get the input using document.activeElement or evt.target but since the inputs are controlled by the store state I can't change their values... Any ideas?

** Update **

To make things more clear... I would like to make my App behave like a "desktop app", no matter in which input I'm in my app, if I press the key combination it will put a special char in that input, that means, it would be handled by the onChange. (I'm not that familiar with React or JS, so maybe I'm asking too much..)

So I would have an onKeyPress in my high order component that would handle the combination and would trigger the onChange on the active input after adding the special character to the value attribute of the input.

The way I made it happen was to set on each input an onKeyPress that will look for the combination and send the same action as my onChange but with the special character in the text.

<input
    onKeyPress={(evt)=>{
        /* ... Check combination ... */
        let text = _addSpecialChar(evt.target.value);
        MyActions.update(text);
    }}
    onChange={(evt)=>{
        MyActions.update(evt.target.value);
    }}
/>

As I said above I would like to handle the combination with the onChange, as a normal character so I don't have to add the onKeyPress on every input. Is this possible?


Solution

  • Ah thanks, your update made things more clear. Can you try to manually trigger a change event on the input once you enter the emoji?

    handleShortcut(evt) {
        if (evt.keyCode === ...) {
            MyActions.addSpecialChar();
            evt.preventDefault();
            // Manually trigger on change here of the active element
            evt.target.onchange();
        }
    }
    

    If you need to simulate a full change event, you can try this:

    // Create a new 'change' event
    var event = new Event('change');
    
    // Dispatch it.
    evt.target.dispatchEvent(event);