iannbing / react-simple-tree-menu

A simple React tree menu component
MIT License
137 stars 48 forks source link

Scroll to the active item in the list #173

Open AthulNair opened 4 years ago

AthulNair commented 4 years ago

I am using the ItemComponent to show the tree items. My tree is lengthy one and need the same tree to be shown in different pages while i switch the page I need to persist the active menu. So I was thinking to implemente window.scrollto. So any one have the idea how to scroll to that active item.

iannbing commented 4 years ago

If you give an id to each of your nodes, you should be able to get the element and do element.scrollToView().

AthulNair commented 4 years ago

@iannbing do you have any samples which I can check. It will be really helpful

iannbing commented 3 years ago

@AthulNair Just realized that you're using ItemComponent. Then you don't get this out-of-box.

You need to implement your own ItemComponent, and assign an id to it (using key if it's unique in the whole tree). For example,

<TreeMenu data={data}>
      {({ items }) => (
          <ul>
            {items.map(({ key, label, ...props }) => (
               <li key={key} id={key} {...props}>{label}</li>
            ))}
          </ul>
      )}
</TreeMenu>

and in your component

const element = document.getElementById('foo');
element.scrollToView();

The page should scroll to the node with id foo (if it's visible of course).