Working with react to render nested unordered lists from JSON files has been a challenge. I'm trying to find a way to display them with alternating background colors for each line, making the content easier to read.
1 (white)
2 (gray)
3 (white)
4 (gray)
5 (white)
6 (gray)
7 (white)
I attempted to achieve this using pure CSS but ran into issues with the nth-of-type()
selector only checking the relative index. This resulted in an inconsistent color pattern as shown below:
1 (white)
2 (gray)
1 (white)
1 (white)
2 (gray)
2 (gray)
3 (white)
Next, I tried incorporating a counter in my recursive rendering function to determine the even and odd lines, but encountered further challenges:
1 (white)
2 (gray)
4 (gray)
6 (gray)
7 (white)
5 (white)
3 (white)
I understand that flattening the tree structure and utilizing a matching field to establish the even/odd sequence could be a solution, however, it seems inefficient both in terms of time and space.