aboutsummaryrefslogtreecommitdiff
path: root/src/components/Sidebar/Item.js
blob: 88b69df2fc65e93d6b83859f84899a5beffe3b3d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/** @jsx jsx */
import { useRef } from "react";
import { jsx } from "theme-ui";
import ItemTitle from "./ItemTitle";

export const isItemActive = (activeItemParentLinks, item) => {
  if (activeItemParentLinks) {
    for (const parentLink of activeItemParentLinks) {
      if (parentLink === item.link) {
        return true;
      }
    }
  }

  return false;
};

function Item({
  item,
  location,
  openItems,
  activeItem,
  activeItemParentLinks,
  toggleItem
}) {
  const isParentOfActiveItem = isItemActive(activeItemParentLinks, item);
  const isActive = item.link === location.pathname || isParentOfActiveItem;

  const isExpanded = openItems[item.link];

  const id = useRef(item.link.replace(/\W+/g, "")).current;

  return (
    <li>
      <ItemTitle
        id={id}
        item={item}
        isActive={isActive}
        isExpanded={isExpanded}
        toggleItem={toggleItem}
      />

      {item.items && (
        <ul id={id} sx={{ display: isExpanded ? "block" : "none" }}>
          {item.items.map(subitem => (
            <Item
              key={subitem.link}
              item={subitem}
              location={location}
              openItems={openItems}
              activeItem={activeItem}
              activeItemParentLinks={activeItemParentLinks}
              toggleItem={toggleItem}
            />
          ))}
        </ul>
      )}
    </li>
  );
}

export default Item;