-
Notifications
You must be signed in to change notification settings - Fork 58
/
AccordionSection.tsx
93 lines (87 loc) · 2.24 KB
/
AccordionSection.tsx
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import React, { useId } from "react";
import type { ReactNode } from "react";
import type { Headings } from "types";
export type AccordionHeadings = Exclude<Headings, "h1">;
export type Props = {
/**
* The content of the section.
*/
content?: ReactNode;
/**
* An optional value to set the expanded section. The value must match a
* section key.
*/
expanded?: string | null;
headingLevel?: number;
/**
* An optional click event when the title is clicked.
*/
onTitleClick?: (expanded: boolean, key: string) => void;
/**
* An optional key to be used to track which section is selected.
*/
sectionKey?: string;
setExpanded?: (key: string | null, title: ReactNode | null) => void;
/**
* The title of the section.
*/
title?: ReactNode;
/**
* Optional string describing heading element that should be used for the section titles.
*/
titleElement?: AccordionHeadings;
};
const AccordionSection = ({
content,
expanded,
onTitleClick,
sectionKey,
setExpanded,
title,
titleElement,
headingLevel = 3,
}: Props): JSX.Element => {
const sectionId = useId();
const tabId = useId();
const key = sectionKey || sectionId;
const isExpanded = expanded === key;
const Title = titleElement || "div";
return (
<li className="p-accordion__group">
<Title
role={titleElement ? null : "heading"}
aria-level={titleElement ? null : headingLevel}
className="p-accordion__heading"
>
<button
aria-controls={`#${sectionId}`}
aria-expanded={isExpanded ? "true" : "false"}
className="p-accordion__tab"
id={tabId}
onClick={() => {
if (isExpanded) {
setExpanded(null, null);
} else {
setExpanded(key, title);
}
onTitleClick && onTitleClick(!isExpanded, key);
}}
role="tab"
type="button"
>
{title}
</button>
</Title>
<section
aria-hidden={isExpanded ? "false" : "true"}
aria-labelledby={tabId}
className="p-accordion__panel"
id={sectionId}
role="tabpanel"
>
{content}
</section>
</li>
);
};
export default AccordionSection;