Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 580
soywod Avatar asked Nov 06 '25 03:11

soywod


1 Answers

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.

like image 72
David Bradshaw Avatar answered Nov 08 '25 20:11

David Bradshaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!