1

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
  • 31
  • 2
  • 2
    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

0

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
  • 615
  • 9
  • 22