Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How to shift focus using arrow keys? (TreeView)

I am looking for solution which allow to focus elements inside treeview using arrow keys.

Currently, I have treeView (ul) and treeNode (li). Each treeNode may have their own treeView and so on. Every treeNode has tabIndex="0" property to add possibility navigate trough the treeView using Tab key. It works fine. But I would like to add keyboard arrow support to do the same thing.

Any idea how to do this? P.S. I don't want to use any 3rd party libs expect pure React, JS.

<section>
  <header>
    { title }
  </header>
  <ul>
    <li>
      <section>
        <header>
          { title }
        </header>
        <ul>
          // etc.
        </ul>
      </section>
    </li>
  </ul>
<section>
like image 243
Roman Mahotskyi Avatar asked Jun 28 '17 14:06

Roman Mahotskyi


1 Answers

I have found a solution to move focus within treeView. First of all you should find all your nodes inside your tree. Then you can find focused element using document.activeElement. After that, you be able to find this item within your array nodes. (document.activeElement == nodes[i]) and remember index i. To move focus using arrow keys, just add eventListener to your node and handle it.

For example, to move upward you can do something like this:

if(arrowUp) { elements[i + 1].focus() }

like image 109
Roman Mahotskyi Avatar answered Oct 16 '22 23:10

Roman Mahotskyi