react-router-dom#useMatch TypeScript Examples
The following examples show how to use
react-router-dom#useMatch.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BottomNav.tsx From atlas with GNU General Public License v3.0 | 6 votes |
Link: React.FC<typeof viewerNavItems[number]> = ({ to, icon, name }) => {
const match = useMatch(to)
return (
<NavLink to={to} active={match}>
{icon}
<NavTitle variant="t100-strong">{name}</NavTitle>
</NavLink>
)
}
Example #2
Source File: renderContent.tsx From Search-Next with GNU General Public License v3.0 | 6 votes |
RenderContent: React.FC<RenderContentProps> = (props) => {
const { children, pathname, noOutlet = false } = props;
const location = useLocation();
let match = useMatch(pathname);
return (
<>
{(pathname === location.pathname ||
pathname === match?.pattern?.path ||
(pathname && pathname.indexOf('undefined') !== -1)) &&
children}
{!noOutlet && <Outlet />}
</>
);
}
Example #3
Source File: Programs.tsx From gear-js with GNU General Public License v3.0 | 6 votes |
Programs: VFC = () => {
const isUploadedProgramsPage = useMatch(routes.uploadedPrograms);
const isAllProgramsPage = useMatch(routes.allPrograms);
const isAllMessagesPage = useMatch(routes.messages);
let currentPage = SWITCH_PAGE_TYPES.UPLOAD_PROGRAM;
if (isUploadedProgramsPage) {
currentPage = SWITCH_PAGE_TYPES.UPLOADED_PROGRAMS;
} else if (isAllProgramsPage) {
currentPage = SWITCH_PAGE_TYPES.ALL_PROGRAMS;
} else if (isAllMessagesPage) {
currentPage = SWITCH_PAGE_TYPES.ALL_MESSAGES;
}
return (
<div className="main-content-wrapper">
<ProgramSwitch pageType={currentPage} />
{currentPage === SWITCH_PAGE_TYPES.UPLOAD_PROGRAM && (
<>
<DndProvider backend={HTML5Backend}>
<Upload />
</DndProvider>
<BlockList />
</>
)}
{currentPage === SWITCH_PAGE_TYPES.UPLOADED_PROGRAMS && <Recent />}
{currentPage === SWITCH_PAGE_TYPES.ALL_PROGRAMS && <All />}
{currentPage === SWITCH_PAGE_TYPES.ALL_MESSAGES && <Messages />}
</div>
);
}
Example #4
Source File: Document.tsx From gear-js with GNU General Public License v3.0 | 6 votes |
Document: VFC = () => {
const isPrivacyPolicyPage = useMatch(routes.privacyPolicy);
return (
<>
{isPrivacyPolicyPage ? <PrivacyPolicy /> : <TermsOfUse />}
<DocumentFooter />
</>
);
}
Example #5
Source File: NavItem.tsx From atlas with GNU General Public License v3.0 | 6 votes |
NavItem: React.FC<NavItemProps> = ({
expanded = false,
subitems,
children,
to,
onClick,
itemName,
badgeNumber,
isSecondary,
}) => {
const { height: subitemsHeight, ref: subitemsRef } = useResizeObserver<HTMLUListElement>({ box: 'border-box' })
const match = useMatch(to)
return (
<SidebarNavItem data-badge={badgeNumber} expanded={expanded}>
<SidebarNavLink
onClick={onClick}
data-active={match ? 'true' : ''}
to={to}
expanded={expanded || undefined}
content={itemName || ''}
isSecondary={isSecondary}
>
{children}
</SidebarNavLink>
{subitems && (
<SubItemsWrapper expanded={expanded} subitemsHeight={subitemsHeight}>
<ul ref={subitemsRef}>
{subitems.map((item) => (
<SubItem key={item.name}>
<a>{item.name}</a>
</SubItem>
))}
</ul>
</SubItemsWrapper>
)}
</SidebarNavItem>
)
}
Example #6
Source File: DesktopHeader.tsx From anchor-web-app with Apache License 2.0 | 6 votes |
function NavMenu({ to, title }: RouteMenu) {
const match = useMatch({
path: to,
});
return (
<div data-active={!!match}>
<Link to={to}>{title}</Link>
</div>
);
}
Example #7
Source File: bluna.convert.tsx From anchor-web-app with Apache License 2.0 | 6 votes |
function Component({ className }: UIElementProps) {
const navigate = useNavigate();
const match = useMatch({ path: '/basset/bluna/:page', end: true });
const tab = useMemo<Item | undefined>(() => {
return tabItems.find(({ value }) => value === match?.params.page);
}, [match?.params.page]);
const tabChange = useCallback(
(nextTab: Item) => {
navigate(`/basset/bluna/${nextTab.value}`);
},
[navigate],
);
return (
<CenteredLayout maxWidth={800} className={className}>
<TitleContainer>
<PageTitle title="MINT & BURN" />
</TitleContainer>
<Tab
className="tab"
items={tabItems}
selectedItem={tab ?? tabItems[0]}
onChange={tabChange}
labelFunction={({ label }) => label}
keyFunction={({ value }) => value}
tooltipFunction={({ tooltip }) => tooltip}
/>
<Outlet />
</CenteredLayout>
);
}
Example #8
Source File: MobileHeader.tsx From anchor-web-app with Apache License 2.0 | 6 votes |
function NavMenu({
to,
title,
close,
}: RouteMenu & {
close: () => void;
}) {
const match = useMatch({
path: to,
});
return (
<div data-active={!!match}>
<NavLink to={to} onClick={close}>
{title}
</NavLink>
</div>
);
}
Example #9
Source File: useAirdropElement.tsx From anchor-web-app with Apache License 2.0 | 6 votes |
export function useAirdropElement(open: boolean, isMobileLayout: boolean) {
const { data: airdrop, isLoading: airdropIsLoading } = useAirdropCheckQuery();
const matchAirdrop = useMatch('/airdrop');
const [airdropClosed, setAirdropClosed] = useState(() => _airdropClosed);
const closeAirdrop = useCallback(() => {
setAirdropClosed(true);
_airdropClosed = true;
}, []);
return useMemo(() => {
return airdrop &&
!open &&
!airdropClosed &&
!airdropIsLoading &&
!matchAirdrop ? (
<AirdropContent onClose={closeAirdrop} isMobileLayout={isMobileLayout} />
) : null;
}, [
airdrop,
airdropClosed,
airdropIsLoading,
closeAirdrop,
matchAirdrop,
open,
isMobileLayout,
]);
}
Example #10
Source File: rewards.anc-governance.tsx From anchor-web-app with Apache License 2.0 | 5 votes |
function RewardsAncUstLpBase({ className }: RewardsAncUstLpProps) {
const navigate = useNavigate();
const pageMatch = useMatch(`/${ancGovernancePathname}/:view`);
const subTab = useMemo<Item | undefined>(() => {
switch (pageMatch?.params.view) {
case 'stake':
return stakeItems[0];
case 'unstake':
return stakeItems[1];
}
}, [pageMatch?.params.view]);
const subTabChange = useCallback(
(nextTab: Item) => {
navigate({
pathname: `/${ancGovernancePathname}/${nextTab.value}`,
});
},
[navigate],
);
return (
<CenteredLayout className={className}>
<header>
<h1>
<Circles radius={24} backgroundColors={['#2C2C2C']}>
<GifIcon
src={anc80gif}
style={{ fontSize: '2em', borderRadius: '50%' }}
/>
</Circles>
ANC Governance
</h1>
</header>
<Section>
<RulerTab
className="subtab"
items={stakeItems}
selectedItem={subTab ?? stakeItems[0]}
onChange={subTabChange}
labelFunction={({ label }) => label}
keyFunction={({ value }) => value}
tooltipFunction={({ tooltip }) => tooltip}
/>
<div className="form">
<Routes>
<Route path="/stake" element={<AncGovernanceStake />} />
<Route path="unstake" element={<AncGovernanceUnstake />} />
<Route
index={true}
element={<Navigate to={`/${ancGovernancePathname}/stake`} />}
/>
<Route
path="*"
element={<Navigate to={`/${ancGovernancePathname}/stake`} />}
/>
</Routes>
<Outlet />
</div>
</Section>
</CenteredLayout>
);
}
Example #11
Source File: trade.tsx From anchor-web-app with Apache License 2.0 | 5 votes |
function TradeBase({ className }: RewardsPoolProps) {
const navigate = useNavigate();
const pageMatch = useMatch(`/trade/:view`);
const tab = useMemo<Item | undefined>(() => {
switch (pageMatch?.params.view) {
case 'buy':
return tabItems[0];
case 'sell':
return tabItems[1];
}
}, [pageMatch?.params.view]);
const tabChange = useCallback(
(nextTab: Item) => {
navigate({
pathname: nextTab.value === 'sell' ? `/trade/sell` : `/trade/buy`,
});
},
[navigate],
);
return (
<CenteredLayout className={className}>
<Tab
className="tab"
items={tabItems}
selectedItem={tab ?? tabItems[0]}
onChange={tabChange}
labelFunction={({ label }) => label}
keyFunction={({ value }) => value}
tooltipFunction={({ tooltip }) => tooltip}
/>
<Section>
<Routes>
<Route path="" element={<Navigate to="/trade/buy" />} />
<Route path="/buy" element={<TradeBuy />} />
<Route path="/sell" element={<TradeSell />} />
<Route path="*" element={<Navigate to="/trade/buy" />} />
</Routes>
<Outlet />
</Section>
</CenteredLayout>
);
}
Example #12
Source File: wh.convert.tsx From anchor-web-app with Apache License 2.0 | 5 votes |
function Component({ className }: UIElementProps) {
const navigate = useNavigate();
const match = useMatch({ path: '/basset/wh/:tokenSymbol/:page', end: true });
const { data: bAssetInfo } = useBAssetInfoByTokenSymbolQuery(
match?.params.tokenSymbol,
);
const tabItems = useMemo<Item[]>(() => {
const bAssetSymbol = bAssetInfo
? bAssetInfo.tokenDisplay.anchor?.symbol ?? bAssetInfo.bAsset.symbol
: 'ASSET';
const whAssetSymbol = bAssetInfo
? bAssetInfo.tokenDisplay.wormhole.symbol
: 'whASSET';
return [
{
label: `to ${bAssetSymbol}`,
value: 'to-basset',
tooltip:
'Convert wormhole tokens into bAssets that are useable on Anchor.',
},
{
label: `to ${whAssetSymbol}`,
value: 'to-wbasset',
tooltip: 'Convert bAssets useable on Anchor into wormhole tokens.',
},
];
}, [bAssetInfo]);
const tab = useMemo<Item | undefined>(() => {
return tabItems.find(({ value }) => value === match?.params.page);
}, [match?.params.page, tabItems]);
const tabChange = useCallback(
(nextTab: Item) => {
navigate(`/basset/wh/${match?.params.tokenSymbol}/${nextTab.value}`);
},
[navigate, match?.params.tokenSymbol],
);
return (
<CenteredLayout className={className} maxWidth={800}>
<TitleContainer>
<PageTitle
title="CONVERT"
tooltip="Tokens transferred to the terra chain through wormhole must be converted to bAssets useable on Anchor to be deposited as collateral."
/>
</TitleContainer>
<Tab
className="tab"
items={tabItems}
selectedItem={tab ?? tabItems[0]}
onChange={tabChange}
labelFunction={({ label }) => label}
keyFunction={({ value }) => value}
tooltipFunction={({ tooltip }) => tooltip}
/>
<Outlet />
</CenteredLayout>
);
}
Example #13
Source File: App.tsx From genshin-optimizer with MIT License | 5 votes |
function MatchTitle() {
const { t } = useTranslation("ui")
let { params: { page = "" } } = useMatch({ path: "/:page" }) ?? { params: { page: "" } }
useTitle(page && t(`tabs.${page}`))
return null
}
Example #14
Source File: Header.tsx From genshin-optimizer with MIT License | 5 votes |
function HeaderContent({ anchor }) {
const theme = useTheme();
const isLarge = useMediaQuery(theme.breakpoints.up('lg'));
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
const { t } = useTranslation("ui")
const { params: { currentTab } } = useMatch({ path: "/:currentTab", end: false }) ?? { params: { currentTab: "" } };
if (isMobile) return <MobileHeader anchor={anchor} currentTab={currentTab} />
return <AppBar position="static" sx={{ bgcolor: "#343a40", display: "flex", flexWrap: "nowrap" }} elevation={0} id={anchor} >
<Tabs
value={currentTab}
variant="scrollable"
scrollButtons="auto"
sx={{
"& .MuiTab-root": {
px: 1,
flexDirection: "row",
minWidth: 40,
minHeight: "auto",
},
"& .MuiTab-root:hover": {
transition: "background-color 0.5s ease",
backgroundColor: "rgba(255,255,255,0.1)"
},
"& .MuiTab-root > .MuiTab-iconWrapper": {
mb: 0,
mr: 0.5
},
}}
>
<Tab value="" component={RouterLink} to="/" label={<Typography variant="h6" sx={{ px: 1 }}>
<Trans t={t} i18nKey="pageTitle">Genshin Optimizer</Trans>
</Typography>} />
{content.map(({ i18Key, value, to, svg }) => <Tab key={value} value={value} component={RouterLink} to={to} icon={<FontAwesomeIcon icon={svg} />} label={t(i18Key)} />)}
<Box flexGrow={1} />
{links.map(({ i18Key, href, label, svg }) => <Tab key={label} component="a" href={href} target="_blank" icon={<FontAwesomeIcon icon={svg} />} onClick={e => ReactGA.outboundLink({ label }, () => { })} label={isLarge && t(i18Key)} />)}
</Tabs>
</AppBar>
}
Example #15
Source File: index.tsx From genshin-optimizer with MIT License | 5 votes |
function CharacterDisplayCard({ characterKey, newteamData, mainStatAssumptionLevel = 0, onClose }: CharacterDisplayCardProps) {
const teamData = useTeamData(characterKey, mainStatAssumptionLevel)
const { character, characterSheet, target: charUIData } = teamData?.[characterKey] ?? {}
let { params: { tab = "overview" } } = useMatch({ path: "/characters/:charKey/:tab", end: false }) ?? { params: { tab: "overview" } }
const { t } = useTranslation()
useTitle(`${t(`char_${characterKey}_gen:name`)} - ${t(`page_character:tabs.${tab}`)}`)
const characterDispatch = useCharacterReducer(character?.key ?? "")
const { compareData } = character ?? {}
const dataContextValue: dataContextObj | undefined = useMemo(() => {
if (!teamData || !character || !characterSheet || !charUIData) return undefined
return {
character,
characterSheet,
mainStatAssumptionLevel,
data: (newteamData ? newteamData[characterKey]!.target : charUIData),
teamData: (newteamData ? newteamData : teamData),
oldData: (compareData && newteamData) ? charUIData : undefined,
characterDispatch
}
}, [character, characterSheet, mainStatAssumptionLevel, newteamData, charUIData, teamData, characterDispatch, characterKey, compareData])
if (!teamData || !character || !characterSheet || !charUIData || !dataContextValue) return <></>
return <CardDark >
<DataContext.Provider value={dataContextValue}>
<CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
<Grid container spacing={1}>
<Grid item>
<CharSelectDropdown />
</Grid>
<Grid item flexGrow={1} />
{!!mainStatAssumptionLevel && <Grid item><Card sx={{ p: 1, bgcolor: t => t.palette.warning.dark }}><Typography><strong>Assume Main Stats are Level {mainStatAssumptionLevel}</strong></Typography></Card></Grid>}
{!!onClose && <Grid item>
<CloseButton onClick={onClose} />
</Grid>}
</Grid>
<CardLight>
<TabNav tab={tab} />
</CardLight>
<FormulaCalcCard />
<EnemyExpandCard />
<Suspense fallback={<Skeleton variant="rectangular" width="100%" height={500} />}>
<Routes>
{/* Character Panel */}
<Route index element={<TabOverview />} />
<Route path="/talent" element={<TabTalent />} />
<Route path="/equip" element={<TabEquip />} />
<Route path="/teambuffs" element={<TabTeambuffs />} />
<Route path="/optimize" element={<TabBuild />} />
</Routes>
</Suspense>
<CardLight>
<TabNav tab={tab} />
</CardLight>
</CardContent>
</DataContext.Provider>
</CardDark>
}
Example #16
Source File: index.tsx From genshin-optimizer with MIT License | 5 votes |
export default function PageDocumentation() {
// const { t } = useTranslation("documentation")
ReactGA.send({ hitType: "pageview", page: '/doc' })
const { params: { currentTab } } = useMatch("/doc/:currentTab") ?? { params: { currentTab: "" } }
return <CardDark sx={{ my: 1 }}>
<Grid container sx={{ px: 2, py: 1 }}>
<Grid item flexGrow={1}>
<Typography variant="h6">
Documentation
</Typography>
</Grid>
<Grid item>
<Typography variant="h6">
<SqBadge color="info">Version. 2</SqBadge>
</Typography>
</Grid>
</Grid>
<Divider />
<CardContent>
<Grid container spacing={1}>
<Grid item xs={12} md={2}>
<CardLight sx={{ height: "100%" }}>
<Tabs
orientation="vertical"
value={currentTab}
aria-label="Documentation Navigation"
sx={{ borderRight: 1, borderColor: 'divider' }}
>
<Tab label="Overview" value="" component={Link} to="" />
<Tab label={"Key naming convention"} value="KeyNaming" component={Link} to="KeyNaming" />
<Tab label={<code>StatKey</code>} value="StatKey" component={Link} to="StatKey" />
<Tab label={<code>ArtifactSetKey</code>} value="ArtifactSetKey" component={Link} to="ArtifactSetKey" />
<Tab label={<code>CharacterKey</code>} value="CharacterKey" component={Link} to="CharacterKey" />
<Tab label={<code>WeaponKey</code>} value="WeaponKey" component={Link} to="WeaponKey" />
<Tab label={<code>MaterialKey</code>} value="MaterialKey" component={Link} to="MaterialKey" />
<Tab label={"Version History"} value="VersionHistory" component={Link} to="VersionHistory" />
</Tabs>
</CardLight>
</Grid>
<Grid item xs={12} md={10}>
<CardLight sx={{ height: "100%" }}>
<CardContent>
<Suspense fallback={<Skeleton variant="rectangular" width="100%" height={600} />}>
<Routes>
<Route index element={<Overview />} />
<Route path="/VersionHistory" element={<VersionHistoryPane />} />
<Route path="/MaterialKey" element={<MaterialKeyPane />} />
<Route path="/ArtifactSetKey" element={<ArtifactSetKeyPane />} />
<Route path="/WeaponKey" element={<WeaponKeyPane />} />
<Route path="/CharacterKey" element={<CharacterKeyPane />} />
<Route path="/StatKey" element={<StatKeyPane />} />
<Route path="/KeyNaming" element={<KeyNamingPane />} />
</Routes>
</Suspense>
</CardContent>
</CardLight>
</Grid>
</Grid>
</CardContent>
</CardDark>
}
Example #17
Source File: VestingClaimNotification.tsx From anchor-web-app with Apache License 2.0 | 5 votes |
export function useVestingClaimNotification(): VestingClaimNotificationReturn {
const { data: { vestingAccount } = {} } = useAncVestingAccountQuery();
const matchAncVestingClaim = useMatch('/anc/vesting/claim');
const [open, setOpen] = useState(true);
const yesterday = new Date(new Date().getTime() - 86400000);
const [ignoreUntil, setIgnoreUntil] = useLocalStorage(
'__anchor_ignore_vesting_claim',
yesterday.toISOString(),
);
const setIgnore = useCallback(() => {
const timestamp = new Date(new Date().getTime() + 86400000).toISOString();
setIgnoreUntil(timestamp);
// this is not the best idea but saves having to split out the vesting
// claim into a provider/context pattern and its short term anyway
(window as any).__anchor_ignore_vesting_claim = timestamp;
}, [setIgnoreUntil]);
const ignore = (window as any).__anchor_ignore_vesting_claim ?? ignoreUntil;
const showNotification =
open &&
!matchAncVestingClaim &&
vestingAccount &&
new Dec(vestingAccount.accrued_anc).gt(0) &&
new Date(ignore) < new Date();
return [
showNotification ? (
<DropdownContainer>
<DropdownBox>
<VestingClaimNotification
onClose={(ignored) => {
setOpen(false);
if (ignored) {
setIgnore();
}
}}
/>
</DropdownBox>
</DropdownContainer>
) : undefined,
setIgnore,
];
}
Example #18
Source File: rewards.anc-ust-lp.tsx From anchor-web-app with Apache License 2.0 | 4 votes |
function RewardsAncUstLpBase({ className }: RewardsAncUstLpProps) {
const navigate = useNavigate();
const pageMatch = useMatch(`/${ancUstLpPathname}/:view`);
const tab = useMemo<Item | undefined>(() => {
switch (pageMatch?.params.view) {
case 'provide':
case 'withdraw':
return tabItems[0];
case 'stake':
case 'unstake':
return tabItems[1];
}
}, [pageMatch?.params.view]);
const tabChange = useCallback(
(nextTab: Item) => {
navigate(
nextTab.value === 'stake'
? `/${ancUstLpPathname}/stake`
: `/${ancUstLpPathname}/provide`,
);
},
[navigate],
);
const subTab = useMemo<Item | undefined>(() => {
switch (pageMatch?.params.view) {
case 'provide':
return poolItems[0];
case 'withdraw':
return poolItems[1];
case 'stake':
return stakeItems[0];
case 'unstake':
return stakeItems[1];
}
}, [pageMatch?.params.view]);
const subTabChange = useCallback(
(nextTab: Item) => {
navigate(`/${ancUstLpPathname}/${nextTab.value}`);
},
[navigate],
);
return (
<CenteredLayout className={className}>
<header>
<h1>
<Circles radius={24} backgroundColors={['#ffffff', '#2C2C2C']}>
<TokenIcon token="ust" style={{ fontSize: '1.1em' }} />
<GifIcon
src={anc80gif}
style={{ fontSize: '2em', borderRadius: '50%' }}
/>
</Circles>
ANC-UST LP
</h1>
<Tab
items={tabItems}
selectedItem={tab ?? tabItems[0]}
onChange={tabChange}
labelFunction={({ label }) => label}
keyFunction={({ value }) => value}
height={46}
borderRadius={30}
fontSize={12}
/>
</header>
<Section>
<RulerTab
className="subtab"
items={tab?.value === 'stake' ? stakeItems : poolItems}
selectedItem={
subTab ?? (tab?.value === 'stake' ? stakeItems[0] : poolItems[0])
}
onChange={subTabChange}
labelFunction={({ label }) => label}
keyFunction={({ value }) => value}
tooltipFunction={({ tooltip }) => tooltip}
/>
<div className="form">
{tab?.value === 'stake' && <AncUstLpStakeOverview />}
<Routes>
<Route path={`/provide`} element={<AncUstLpProvide />} />
<Route path={`/withdraw`} element={<AncUstLpWithdraw />} />
<Route path={`/stake`} element={<AncUstLpStake />} />
<Route path={`/unstake`} element={<AncUstLpUnstake />} />
<Route
path={``}
element={<Navigate to={`/${ancUstLpPathname}/provide`} />}
/>
<Route
path={`*`}
element={<Navigate to={`/${ancUstLpPathname}/provide`} />}
/>
</Routes>
<Outlet />
</div>
</Section>
</CenteredLayout>
);
}