import React, { FunctionComponent, ReactNode, useEffect, useState } from 'react'; import { useHistory, useLocation, useRouteMatch } from 'react-router'; import { Link } from 'react-router-dom'; export interface Tab { route: string name: string icon ?: string render: (tab: Tab) => ReactNode } export interface RoutedTabsProps { tabs: Tab[] baseRoute?: string defaultTabIndex?: number } export const RoutedTabs: FunctionComponent = ({ tabs, baseRoute, defaultTabIndex }) => { const history = useHistory(); const location = useLocation(); const tabRoute = (route: string): string => { return `${baseRoute}${route}`; }; const [ selectedTabIndex, setSelectedTabIndex ] = useState(defaultTabIndex || 0); const expectedTab = tabs[selectedTabIndex]; const expectedTabRoute = tabRoute(expectedTab.route); let matchExpectedTabRoute = useRouteMatch(expectedTabRoute); useEffect(() => { if (matchExpectedTabRoute) return; const newTabIndex = tabs.findIndex(t => location.pathname === tabRoute(t.route)); if (newTabIndex !== -1) { selectTab(newTabIndex); return; } history.push(expectedTabRoute); }, [matchExpectedTabRoute]); const selectTab = (tabIndex: number) => { setSelectedTabIndex(tabIndex); const newTab = tabs[tabIndex]; history.push(tabRoute(newTab.route)); }; return (
{ expectedTab.render(expectedTab) }
); }