Skip to content

Commit

Permalink
fix: navigate tabs as params
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Jul 1, 2023
1 parent 027acff commit 7ac963d
Showing 1 changed file with 34 additions and 12 deletions.
46 changes: 34 additions & 12 deletions src/components/page/TabBar.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import React from 'react';
import {
useParams,
useNavigate,
generatePath
} from 'react-router-dom';
import {
Tabs,
Tab,
Expand All @@ -10,34 +15,47 @@ import {
ChevronLeft as ChevronLeftIcon,
ChevronRight as ChevronRightIcon
} from '@mui/icons-material';
import {
object as YupObject,
string as YupString
} from 'yup';

import { primary } from '../../theme/colors';
import { tryValidateSync } from '../../helpers/yup';
import Section, { SectionElement } from './Section';

import { SearchParams } from '../../helpers';

export interface TabBarProps {
header: string;
tabs: Array<{
label: string;
children: SectionElement | SectionElement[];
path: string;
}>;
originalPath: string;
}

const TabBar: React.FC<TabBarProps> = ({
header,
tabs
tabs,
originalPath
}) => {
const params = useParams();
const navigate = useNavigate();
const [value, setValue] = React.useState(0);

const labels = tabs.map(tab => tab.label);
const children = tabs.map(tab => tab.children);
const paths = tabs.map(tab => tab.path);

const params = SearchParams.get<{ tab: string; }>({
tab: { validate: SearchParams.validate.inOptions(labels) }
});
React.useEffect(() => {
const tab = tryValidateSync(params, YupObject({
tab: YupString().oneOf(paths).required()
}))?.tab;

const [value, setValue] = React.useState(
params === null ? 0 : labels.indexOf(params.tab)
);
if (tab !== undefined) {
setValue(paths.indexOf(tab));
}
}, [params]);

return <>
<Section
Expand All @@ -61,7 +79,11 @@ const TabBar: React.FC<TabBarProps> = ({
>
<Tabs
value={value}
onChange={(_, value) => { setValue(value); }}
onChange={(_, value) => {
navigate(generatePath(originalPath, {
tab: paths[value]
}));
}}
ScrollButtonComponent={({
disabled,
onClick,
Expand All @@ -88,8 +110,8 @@ const TabBar: React.FC<TabBarProps> = ({
)}</>;
}}
>
{tabs.map((tab) =>
<Tab key={tab.label} label={tab.label} />
{labels.map((label) =>
<Tab key={label} label={label} />
)}
</Tabs>
</Section>
Expand Down

0 comments on commit 7ac963d

Please sign in to comment.