/
index.tsx
72 lines (61 loc) · 1.84 KB
/
index.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
import { useRouter } from "next/router";
import React from "react";
import TabHeader from "./components/tab-header";
type tabProps = {
tabItems: { name: string; component: React.ReactNode }[] | null;
theme?: string;
};
const Tab = ({ tabItems, theme }: tabProps) => {
const router = useRouter();
const defaultTabContent = tabItems && tabItems[0].component;
const [activeTabContent, setActiveTabContent] =
React.useState(defaultTabContent);
const handleActiveTabContent = (index: number) => {
const tabContentName = tabItems && tabItems[index].name;
const tabContent = tabItems && tabItems[index].component;
setActiveTabContent(tabContent);
const encodedTabName: string =
// @ts-ignore
encodeURIComponent(tabContentName).toLocaleLowerCase();
const replaceEncodingParam = encodedTabName.split("%20").join("-");
router.replace(
{
pathname: router.pathname,
query: {
...router.query,
tab: replaceEncodingParam,
},
},
undefined,
{ shallow: true }
);
};
React.useEffect(() => {
const {
query: { tab },
} = router;
let activeTabIndex;
// @ts-ignore
const decodedTab: string =
typeof tab === "string" && tab && tab.match(/-/g)
? tab.split("-").join(" ")
: tab;
const tabNames = tabItems?.map(({ name }) => name);
const tabComponents = tabItems?.map(({ component }) => component);
if (tabNames?.includes(decodedTab, 0)) {
activeTabIndex = tabNames?.indexOf(decodedTab);
setActiveTabContent(tabComponents && tabComponents[activeTabIndex]);
}
}, [router.query.tab, router.pathname]);
return (
<>
<TabHeader
style={theme}
tabItems={tabItems}
components={handleActiveTabContent}
/>
{activeTabContent}
</>
);
};
export default Tab;