3

For my React App, all I want to do is take the current functionality of Tab and Shift Tab, but have the Up/Down arrows do same thing.

I know you can kind of emulate this behavior with Reacts "useRef" and "focus", but my App will have dynamically rendered elements that are always changing.

I am working with a Recursive Component which populates a Recursive Tree based on users input. I also plan to allow the child node order to be sortable (by multiple fields and sorting order).

So there is no (easy) way to know which "ref" the prev/next element would be. This makes "ref.current.focus()" pretty much unusable.

But once the Dom is rendered, the Tab and Shift Tab work exactly like I want...

... I just want to have the Up/Down arrow keys do this instead (i.e. the Up-Arrow would do the Shift Tab action and Down-Arrow would do the Tab action).

Is there anyway to programmatically send a Tab/Shift Tab keystroke in a React App?

Or maybe somehow change focus to the previous/next "sibling" after the DOM is built (i.e. ref.current.nextSibling.focus())?

I can't seem to get any of these approaches to work.

Geoff D
  • 51
  • 3
  • 3
    If those keys do what you want, you could capture the key presses, prevent default, and then "forward" the keypresses to tab/shift tab, as long as something like [this](https://stackoverflow.com/a/43299177/10718641) works for you. – Abe Jan 25 '22 at 05:07

1 Answers1

-1

you can listen to the keypress in componentDidMount()

componentDidMount(){
    document.addEventListener("keydown", this.handleKeyDown);
}

And your handleKeyDown will be;

handleKeyDown(e) {
  e.preventDefault();
  if(e.keyCode == 38){
    //up arrow
    e.dispatchEvent(new Event('keypress', {keyCode: 9}))
  }
}
Akshay K Nair
  • 1,107
  • 16
  • 29
  • Merely dispatching a keyboard event won't engage the browsers default `tabbing` behaviour. – Sadra M. Jul 19 '22 at 07:07
  • also, e is an event. dispatchEvent is on the element. So the correct invocation would be e.currentTarget.dispatchEvent(...) – jessewolfe Oct 24 '22 at 19:43