lukasbach / react-complex-tree

Unopinionated Accessible Tree Component with Multi-Select and Drag-And-Drop
https://rct.lukasbach.com
MIT License
952 stars 77 forks source link

How do I alternate background color of rows? #217

Closed MarksCode closed 1 year ago

MarksCode commented 1 year ago

Has anyone successfully been able to alternate background colors for each row rendered? If so please share how you were able to achieve this. Thanks!

lukasbach commented 1 year ago

Hey! That's not so easy at the moment due to the nature how subtrees are rendered in a nested way, but a hacky solution would be to hook into context object from the tree environment, which contains a "linearItems" prop which contains a list of all tree items in a flattened order, which can be used to find out if an item is even or not. This can then be used in the item render logic to change the display behaviour.

Demo: https://codesandbox.io/s/react-complex-tree-playground-alternating-row-colors-1nu8p6?file=/src/App.tsx

This is a bit inconsistent with updates, where opening a subtree doesn't always directly update the proper colors, so this might need some additional fiddeling to get right.

MarksCode commented 1 year ago

Thanks for the reply. It looks a bit expensive to do the findIndex for each item render unfortunately. It's a bummer because I was going to transition to this library but our design system requires alternating colors 😞

lukasbach commented 1 year ago

Yeah that is true. Another option might be to customize the styling afterwards with the DOM api..

[...document.getElementsByClassName("rct-tree-item-button")]
  .filter((_, i) => i % 2 === 0)
  .forEach(n => n.style.backgroundColor = "red")

You would have to clean it up and rerun it every time the tree updates, so it's definitely far from elegant, but might be a feasible workaround since getElementsByClassName shouldn't be performance-costly.