Search code examples
javascriptreactjseventskeyboard

React trigger KeyboardEvent


I have a PIN code field component that is just a list of inputs wrapped in a React.Fragment. Each time a key is pressed, it focuses the next input. When I reach the last input, I would like to trigger a tabulation to focus the next controller outside of the component (input, button, link etc). I tried to dispatch a KeyboardEvent, but doesn't work:

const evt = new KeyboardEvent("keydown", {
  ...
  code: "Tab",
  key: "Tab",
})

lastInput.dispatchEvent(evt)

Any idea?

Source code: https://github.com/soywod/react-pin-field
Demo : https://react-pin-field.soywod.me/


Solution

  • According to this answer the browser security model stops you simulating the pressing of the Tab Key.

    As an alternative perhaps you could add a nextFocusId attribute to your component and use that to move the curser with document.getElementById().focus() instead.