forked from Katello/katello
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (64 loc) · 1.89 KB
/
index.js
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
import React from 'react';
import { shape, string, number, element, arrayOf } from 'prop-types';
import { Tab, Tabs, TabTitleText } from '@patternfly/react-core';
import { Switch, Route, Redirect, useHistory, useLocation, withRouter, HashRouter } from 'react-router-dom';
import { head, last } from 'lodash';
const RoutedTabs = ({
tabs, defaultTabIndex, titleComponent,
}) => {
const { push } = useHistory();
const {
hash, key: locationKey,
} = useLocation();
// The below transforms #/filters/6 to filters
const currentTabFromUrl = head(last(hash.split('#/')).split('/'));
const onSelect = (_e, eventKey) => {
// This prevents needless pushing on repeated clicks of a tab
if (hash.slice(2) !== eventKey) {
push(`#/${eventKey}`);
}
};
return (
<>
<Tabs
activeKey={currentTabFromUrl}
onSelect={onSelect}
>
{tabs.map(({ key, title }) =>
(
<Tab
aria-label={title}
eventKey={key}
key={key}
title={titleComponent || <TabTitleText>{title}</TabTitleText>}
/>
))}
</Tabs>
<div className="tab-body-with-spacing">
<HashRouter key={locationKey}>
<Switch>
{tabs.map(({ key, content }) => (
<Route key={`${key}-route`} path={`/${key}`}>
{content}
</Route>))}
<Redirect to={`/${currentTabFromUrl || tabs[defaultTabIndex]?.key}`} />
</Switch>
</HashRouter>
</div>
</>
);
};
RoutedTabs.propTypes = {
tabs: arrayOf(shape({
key: string.isRequired,
title: string.isRequired,
content: element.isRequired,
})).isRequired,
defaultTabIndex: number,
titleComponent: element, // when you want to add a custom tab title
};
RoutedTabs.defaultProps = {
defaultTabIndex: 0,
titleComponent: null,
};
export default withRouter(RoutedTabs);