react-router-dom#useRouteMatch JavaScript Examples
The following examples show how to use
react-router-dom#useRouteMatch.
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: Conference.jsx From Consuming-GraphqL-Apollo with MIT License | 6 votes |
export function Conference() {
const { path, url } = useRouteMatch();
return (
<>
<Switch>
<Route path={`${path}/sessions/new`}>
<AddSession />
</Route>
<Route path={`${path}/sessions`}>
<Sessions />
</Route>
<Route path={`${path}/speakers`}>
<Speakers />
</Route>
<Route path={`${path}/speaker/:speaker_id`}>
<Speaker />
</Route>
<Route path={`${path}`}>
<section className="banner">
<img src="images/banner3.png" alt="" />
<div className="inner-content col-md-12">
<div className="container jumboContainer">
<div className="col-md-8 middle">
<HeroLinkButton to={`${url}/speakers`}>
View Speakers
</HeroLinkButton>
<HeroLinkButton to={`${url}/sessions`}>
View Sessions
</HeroLinkButton>
</div>
</div>
</div>
</section>
</Route>
</Switch>
</>
);
}
Example #2
Source File: index.js From clothes-store-micro-frontends with MIT License | 6 votes |
Routes = ({ itemsInCart, setItemsInCart, setNotification }) => {
const { path } = useRouteMatch();
return (
<>
<Route exact path={path}>
<ItemList
itemsInCart={itemsInCart}
setItemsInCart={setItemsInCart}
setNotification={setNotification}
/>
</Route>
<Route path={`${path}/details/:itemId`}>
<ItemDetails
itemsInCart={itemsInCart}
setItemsInCart={setItemsInCart}
setNotification={setNotification}
/>
</Route>
</>
);
}
Example #3
Source File: CategoryContainer.js From covid-break-master with MIT License | 6 votes |
export default function CategoryContainer(props) {
const { id } = useParams()
const match = useRouteMatch()
const categories = []
for(let obj in props.parts) {
categories.push({name: obj, image: props.parts[obj][0].url})
}
const [modal, setModal] = useState(false);
const [displayedItem, setDisplayedItem] = useState()
const toggleModal = () => setModal(!modal);
return (
<CategoryDiv>
{categories.length > 0 && props.parts[`${categories[id].name}`].map((item, index) => {
return (
<>
<ItemDiv onClick={() => {
toggleModal()
setDisplayedItem(item)
}}>
<h3>{item.name}</h3>
<img style={{
maxWidth: "100%",
maxHeight: "173px"
}} src={item.url} />
<p>{item.price}</p>
</ItemDiv>
</>
)
})}
{displayedItem ? <PartsCard toggleModal={toggleModal} modal={modal} part={displayedItem} cart={props.cart} cartRemove={props.cartRemove} cartAdd={props.cartAdd} /> : null}
</CategoryDiv>
)
}
Example #4
Source File: App.js From hk-independent-bus-eta with GNU General Public License v3.0 | 6 votes |
PageSwitch = () => {
const { path } = useRouteMatch()
return (
<Switch>
<Route path={`${path}/route/:id/:panel?`}>
<RouteEta />
</Route>
<Route path={`${path}/settings`}>
<Settings />
</Route>
<Route path={`${path}/search`}>
<RouteBoard />
</Route>
<Route path={`${path}`}>
<Home />
</Route>
</Switch>
)
}
Example #5
Source File: BaseLayout.js From clone-instagram-ui with MIT License | 6 votes |
useRouter = () => {
const params = useParams();
const location = useLocation();
const history = useHistory();
const match = useRouteMatch();
// Return our custom router object
// Memoize so that a new object is only returned if something changes
return useMemo(() => {
return {
// For convenience add push(), replace(), pathname at top level
push: history.push,
replace: history.replace,
pathname: location.pathname,
// Merge params and parsed query string into single "query" object
// so that they can be used interchangeably.
// Example: /:topic?sort=popular -> { topic: "react", sort: "popular" }
query: {
...params,
},
// Include match, location, history objects so we have
// access to extra React Router functionality if needed.
match,
location,
history,
};
}, [params, match, location, history]);
}
Example #6
Source File: _Categories.js From dshop with MIT License | 6 votes |
Categories = () => {
const { config } = useConfig()
const { visibleCollections } = useCollections()
const match = useRouteMatch('/collections/:collection')
const aboutMatch = useRouteMatch('/about')
const affiliateMatch = useRouteMatch('/affiliate')
const active = get(match, 'params.collection')
return (
<div className="categories d-none d-md-block">
<ul className="list-unstyled">
{visibleCollections.map((cat) => (
<Item active={active === cat.id} key={cat.id} id={cat.id}>
{cat.title}
</Item>
))}
<li className={`db ${aboutMatch ? 'active' : ''}`}>
<Link to="/about">
<fbt desc="About">About</fbt>
</Link>
</li>
{!config.affiliates ? null : (
<li className={`${affiliateMatch ? 'active' : ''}`}>
<Link to="/affiliates">
<fbt desc="Affiliates">Affiliates</fbt>
</Link>
</li>
)}
</ul>
<SocialLinks />
</div>
)
}
Example #7
Source File: common.js From actual with MIT License | 6 votes |
export function AnchorLink({
staticContext,
to,
exact,
style,
activeStyle,
children
}) {
let history = useHistory();
let href = history.createHref(typeof to === 'string' ? { pathname: to } : to);
let match = useRouteMatch({ path: to, exact: true });
return (
<NavLink
to={to}
exact={exact}
{...css([styles.smallText, style, match ? activeStyle : null])}
>
{children}
</NavLink>
);
}
Example #8
Source File: index.js From ocp-advisor-frontend with Apache License 2.0 | 6 votes |
RecommendationWrapper = () => {
const intl = useIntl();
const rule = useGetRuleByIdQuery(useParams().recommendationId);
const ack = useGetRecAcksQuery({ ruleId: useParams().recommendationId });
if (rule.isSuccess && rule.data?.content?.description) {
const subnav = `${rule.data.content.description} - Recommendations`;
insights.chrome.updateDocumentTitle(
intl.formatMessage(messages.documentTitle, { subnav })
);
}
const clusters = useGetAffectedClustersQuery(useParams().recommendationId);
useEffect(() => {
rule.refetch();
}, [useParams().recommendationId]);
return (
<Recommendation
rule={rule}
ack={ack}
clusters={clusters}
match={useRouteMatch()}
/>
);
}
Example #9
Source File: Products.js From dshop with MIT License | 6 votes |
AllProducts = () => {
const { collections } = useCollections()
const match = useRouteMatch('/products/:collection')
const collectionId = get(match, 'params.collection')
const collectionTitle = useMemo(() => {
if (!collectionId) return null
const collection = collections.find((c) => c.id == collectionId)
if (collection) return collection.title
return null
}, [collectionId, collections])
return (
<>
<div className="container">
{!collectionTitle ? null : (
<div className="text-center text-4xl font-medium mb-24 font-header">
{collectionTitle}
</div>
)}
<Products />
</div>
</>
)
}
Example #10
Source File: index.js From ocp-advisor-frontend with Apache License 2.0 | 6 votes |
ClusterHeaderWrapper = () => {
const match = useRouteMatch();
const clusterId = match.params.clusterId;
const clusterData = useGetClusterByIdQuery({
id: clusterId,
includeDisabled: false,
});
const clusterInfo = useGetClusterInfoQuery({
id: clusterId,
});
return (
<ClusterHeader
clusterId={clusterId}
clusterData={clusterData}
clusterInfo={clusterInfo}
/>
);
}
Example #11
Source File: Confirmation.js From dshop with MIT License | 6 votes |
Order = () => {
const isMobile = useIsMobile()
const match = useRouteMatch('/order/:tx')
const location = useLocation()
const opts = queryString.parse(location.search)
const { loading, order } = useOrder({
tx: match.params.tx,
password: opts.auth
})
if (loading || !order) return 'Loading'
if (isMobile) {
return <OrderMobile order={order} />
}
return <OrderDesktop order={order} />
}
Example #12
Source File: index.js From ocp-advisor-frontend with Apache License 2.0 | 6 votes |
ClusterWrapper = () => {
const intl = useIntl();
const match = useRouteMatch();
const cluster = useGetClusterByIdQuery({
id: match.params.clusterId,
includeDisabled: false,
});
useEffect(() => {
cluster.refetch();
}, [match.params.clusterId]);
useEffect(() => {
const subnav = `${
cluster?.data?.report?.meta?.cluster_name || match.params.clusterId
} - ${intl.formatMessage(messages.clusters)}`;
insights.chrome.updateDocumentTitle(
intl.formatMessage(messages.documentTitle, { subnav })
);
}, [cluster, match]);
return <Cluster cluster={cluster} match={match} />;
}
Example #13
Source File: useRouter.js From gardener-site with Mozilla Public License 2.0 | 6 votes |
useRouter = () => {
const params = useParams();
const location = useLocation();
const history = useHistory();
const match = useRouteMatch();
return useMemo(() => {
return {
push: history.push,
replace: history.replace,
pathname: location.pathname,
query: {
...queryString.parse(location.search),
...params,
},
match,
location,
history,
};
}, [params, match, location, history]);
}
Example #14
Source File: routing.jsx From MDXP with MIT License | 6 votes |
Routing = ({children}) => {
const {path, url} = useRouteMatch();
return (
<Switch>
<Redirect exact from={path} to={`${url}/0/0`}/>
<Route path={`${path}/:slide/:step`}>
{children}
</Route>
</Switch>
);
}
Example #15
Source File: HiddenSideBar.jsx From Oud with MIT License | 6 votes |
/**
* side bar Element
* @type {Function}
* @param {*} props
* @returns {jsx} element such that change Password , Edit Profile , Account Overview
* <SideBarElenemt>
*/
function SideBarElement(props) {
let { url } = useRouteMatch();
return (
<Dropdown.Item className="listHiddenSideBar">
<Link to={`${url}${props.route}`} id={props.id + " hidden"}>
<span className="icons2">
<i className={props.icon} aria-hidden="true"></i>
</span>
{props.name}
</Link>
</Dropdown.Item>
);
}
Example #16
Source File: Dialogs.jsx From react_53 with MIT License | 6 votes |
// import Dialog from '../Dialog';
function Dialogs() {
const { url } = useRouteMatch();
return (
<div>
<div>
{users.map((item) => (
<Link key={item.url} to={`${url}/${item.url}`}>
{item.fullName}
</Link>
))}
</div>
{/* <div>
<Route path={`${url}:userUrl`} component={Dialog} />
</div> */}
</div>
);
}
Example #17
Source File: index.js From sav3-react with Do What The F*ck You Want To Public License | 6 votes |
function BottomMenu ({className} = {}) {
const classes = useStyles()
const route = useRouteMatch('/:route')
const activeMenu = route && route.params && route.params.route ? route.params.route : 'home'
return (
<Box className={className}>
<BottomNavigation value={activeMenu} className={classes.menu}>
<PublishPostButton />
<BottomNavigationAction component={RouterLink} to='/' value='home' icon={<HomeIcon />} />
<BottomNavigationAction component={RouterLink} to='/search' value='search' icon={<SearchIcon />} />
<BottomNavigationAction component={RouterLink} to='/feed' value='feed' icon={<FeedIcon />} />
<BottomNavigationAction component={RouterLink} to='/peers' value='peers' icon={<PeersIcon />} />
</BottomNavigation>
{/* give real height to fixed bottom nav */}
<Box width={0} className='MuiBottomNavigation-root' />
</Box>
)
}
Example #18
Source File: router.js From code-generator01 with MIT License | 6 votes |
// Custom useRouter hook for getting route data and methods inside any component.
// NOTE: This hook includes all React Router hooks, which can result in extra re-renders
// in some cases. When needed, you can optimize performance by importing the specific hook
// you need (such as useParams or useLocation) instead of this custom useRouter hook.
export function useRouter() {
const params = useParams();
const location = useLocation();
const history = useHistory();
const match = useRouteMatch();
// Return our custom router object
// Memoize so that a new object is only returned if something changes
return useMemo(() => {
return {
// For convenience add push(), replace(), pathname at top level
push: history.push,
replace: history.replace,
pathname: location.pathname,
// Merge params and parsed query string into single "query" object
// so that they can be used interchangeably.
// Example: /:topic?sort=popular -> { topic: "react", sort: "popular" }
query: {
...queryString.parse(location.search), // Convert string to object
...params,
},
// Include match, location, history objects so we have
// access to extra React Router functionality if needed.
match,
location,
history,
};
}, [params, match, location, history]);
}
Example #19
Source File: router.js From app with MIT License | 6 votes |
/**
* Render children based on route config objects
* @param {Array} routes - Routes settings array
* @param {Object} match - Routes settings array
* @param {Object} parentProps - Props to pass to children from parent
* @returns {Array} List of routes
*/
export function renderChildren(routes, parentProps) {
return routes.map((route) => {
const match = useRouteMatch();
const RouteComponent = route.authRequired ? PrivateRoute : Route;
return (
<RouteComponent
key={`${match.url}-${route.path}`}
path={`${match.url}/${route.path}`}
render={(props) => <route.component {...parentProps} {...props} />}
/>
);
});
}
Example #20
Source File: View.jsx From saasgear with MIT License | 6 votes |
ViewDocument = () => {
const match = useRouteMatch();
const documentId = parseInt(match.params.id, 10);
const [fetchDocumentDetail, { data: documentData, loading }] = useLazyQuery(
getDocumentDetailQuery,
);
useEffect(() => {
if (documentId) {
fetchDocumentDetail({ variables: { id: documentId } });
}
}, [documentId]);
function createMarkup(html) {
return {
__html: DOMPurify.sanitize(html),
};
}
return (
<ContentDocument>
{loading && <div>Loading...</div>}
{!loading && documentData?.getDocumentDetail && (
<>
<TitlePage>{documentData.getDocumentDetail.name}</TitlePage>
<ContentPage>
<div
dangerouslySetInnerHTML={createMarkup(
documentData.getDocumentDetail.body,
)}
></div>
</ContentPage>
</>
)}
</ContentDocument>
);
}
Example #21
Source File: Wallet.js From juggernaut-desktop with MIT License | 6 votes |
Wallet = props => {
const { id, info } = props;
const { url } = useRouteMatch();
return (
<div>
<div>WalletID: {id}</div>
<div>Pubkey: {info.identity_pubkey}</div>
<div>Version: {info.version}</div>
<div>Alias: {info.alias}</div>
<div>Color: {info.color}</div>
<div>Active Channels: {info.num_active_channels}</div>
<div>Synced: {info.synced_to_chain.toString()}</div>
<div>Testnet: {info.testnet.toString()}</div>
<Link to={`${url}/chat`}>Open Chat</Link>
<Link to={routes.WALLETS}>Back to Wallets</Link>
</div>
);
}
Example #22
Source File: ChannelLink.jsx From professional-ts with BSD 2-Clause "Simplified" License | 6 votes |
ChannelLink = ({ to, channel }) => {
const match = useRouteMatch(to);
return (
<Link
to={to}
className={
'team-sidebar__channel-link py-1 px-4 no-underline block' +
(match ? 'font-bold bg-teal-700 text-gray-200' : '')
}
>
<span aria-hidden="true"># </span>
{channel.name}
</Link>
);
}
Example #23
Source File: useRouter.js From ant-simple-pro with MIT License | 6 votes |
useRouter=()=> {
const params = useParams();
const location = useLocation();
const history = useHistory();
const match = useRouteMatch();
return useMemo(() => {
return {
push: history.push,
replace: history.replace,
pathname: location.pathname,
// 获取地址栏的参数,将字符串转为json
// 例如: /:topic?sort=popular -> { topic: "react", sort: "popular" }
query: {
...queryString.parse(location.search),
...params
},
match,
location,
history
};
}, [params, match, location, history]);
}
Example #24
Source File: Tabs.jsx From mfe-webpack-demo with MIT License | 5 votes |
export default function TabsComponent() {
const classes = useStyles();
const match = useRouteMatch();
const history = useHistory();
const location = useLocation();
const { path: rootPath } = match;
const handleChange = (event, newValue) => {
history.push(newValue);
};
return (
<div className={classes.root}>
<AppBar position="static">
<Tabs value={location.pathname} onChange={handleChange}>
<Tab label="Foo" value={`${rootPath}/foo`} />
<Tab label="Bar" value={`${rootPath}/bar`} />
</Tabs>
</AppBar>
<Switch>
<Route path={rootPath} exact={true}>
<Redirect to={`${rootPath}/foo`} />
</Route>
<Route path={`${rootPath}/foo`}>
<Typography component="div">
<Box p={3}>Foo Content</Box>
</Typography>
</Route>
<Route path={`${rootPath}/bar`}>
<Typography component="div">
<Box p={3}>
Bar Content
<React.Suspense fallback={null}>
<Button>Bar Button</Button>
</React.Suspense>
</Box>
</Typography>
</Route>
</Switch>
</div>
);
}
Example #25
Source File: Tabs.jsx From module-federation-examples with MIT License | 5 votes |
export default function TabsComponent() {
const classes = useStyles();
const match = useRouteMatch();
const history = useHistory();
const location = useLocation();
const { path: rootPath } = match;
const handleChange = (event, newValue) => {
history.push(newValue);
};
return (
<div className={classes.root}>
<AppBar position="static">
<Tabs value={location.pathname} onChange={handleChange}>
<Tab label="Foo" value={`${rootPath}/foo`} />
<Tab label="Bar" value={`${rootPath}/bar`} />
</Tabs>
</AppBar>
<Switch>
<Route path={rootPath} exact={true}>
<Redirect to={`${rootPath}/foo`} />
</Route>
<Route path={`${rootPath}/foo`}>
<Typography component="div">
<Box p={3}>Foo Content</Box>
</Typography>
</Route>
<Route path={`${rootPath}/bar`}>
<Typography component="div">
<Box p={3}>
Bar Content
<React.Suspense fallback={null}>
<Button>Bar Button</Button>
</React.Suspense>
</Box>
</Typography>
</Route>
</Switch>
</div>
);
}
Example #26
Source File: Header.js From hk-independent-bus-eta with GNU General Public License v3.0 | 5 votes |
Header = (props) => {
const { searchRoute, setSearchRoute } = useContext( AppContext )
const { path } = useRouteMatch()
const { t, i18n } = useTranslation()
const classes = useStyles()
let location = useLocation()
const history = useHistory()
const handleLanguageChange = lang => {
vibrate(1)
history.replace( location.pathname.replace('/'+i18n.language+'/', '/'+lang+'/') )
i18n.changeLanguage(lang)
}
return (
<Toolbar
className={classes.toolbar}
>
<div onClick={() => {
vibrate(1)
history.push(`/${i18n.language}/search`)}
}
>
<Typography variant='subtitle2'>獨立巴士預報</Typography>
</div>
<Input
className={classes.searchRouteInput}
type="text"
value={searchRoute}
placeholder={t('巴士線')}
onChange={e => setSearchRoute(e.target.value)}
onFocus={e => {
vibrate(1)
if ( checkMobile() ) {
document.activeElement.blur()
}
history.replace(`/${i18n.language}/search`)
}}
disabled={path.includes('route')}
/>
<LanguageTabs
value={i18n.language}
onChange={(e, v) => handleLanguageChange(v)}
>
<LanguageTab value="en" label="En" />
<LanguageTab value="zh" label="繁" />
</LanguageTabs>
</Toolbar>
);
}
Example #27
Source File: Docs.jsx From intergalactic with MIT License | 5 votes |
Docs = ({ tokens, tabs }) => {
const match = useRouteMatch();
const [contentModal, setContentModal] = useState(false);
const contentRef = useRef(null);
const prefetch = (route) => {
routes[route]?.loadPage();
};
useEffect(() => {
Prismjs.highlightAllUnder(contentRef.current);
});
const scrollCallback = useScrollHash();
const handleClick = useCallback(
(e) => {
if (e.target.tagName !== 'IMG' || e.defaultPrevented) return;
setContentModal(e.target.outerHTML);
},
[1],
);
const handleModalClose = useCallback(() => {
setContentModal(null);
}, [1]);
return (
<SidebarWrapper>
{Boolean(tabs.length) && (
<div className={styles.tab}>
<TabLine
value={match.url}
size="l"
styles={tabLineStyles}
underlined={false}
mb={6}
className={styles.tabLine}
>
{tabs.map((tab) => {
const { route } = tab;
return (
<TabLine.Item
key={route}
tag={NavLink}
to={`/${route}`}
value={`/${route}/`}
onMouseEnter={() => prefetch(route)}
type="tab"
>
<Text>{tab.metadata.tabName || tab.title}</Text>
</TabLine.Item>
);
})}
</TabLine>
</div>
)}
<main className={styles.main} ref={contentRef} onClick={handleClick}>
<RenderMarkdown tokens={tokens} onRender={scrollCallback} />
</main>
<SideBar />
<ImageFromModal content={contentModal} onClose={handleModalClose} />
</SidebarWrapper>
);
}
Example #28
Source File: index.jsx From redive_linebot with MIT License | 5 votes |
function FullWidthTabs() {
const { url } = useRouteMatch();
const classes = useStyles();
const [value, setValue] = useState(0);
const [BattleTabs, setTabs] = useState([]);
let location = useLocation();
useEffect(() => {
let tabDatas = [
{ label: "戰隊簽到表", link: `${url}/SignTable` },
{ label: "戰隊設定", link: `${url}/Config` },
];
setTabs(tabDatas);
let idx = tabDatas.findIndex(data => location.pathname.indexOf(data.link) !== -1);
if (idx !== -1) setValue(idx);
}, [location.pathname]);
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<div className={classes.root}>
<AppBar position="static" color="default">
<Tabs
value={value}
onChange={handleChange}
indicatorColor="primary"
textColor="primary"
variant="fullWidth"
aria-label="full width tabs example"
>
{BattleTabs.map((tab, index) => (
<Tab
key={index}
label={tab.label}
component={Link}
to={tab.link}
{...a11yProps(index)}
/>
))}
</Tabs>
</AppBar>
</div>
);
}
Example #29
Source File: MenuPanel.js From tulip-frontend with GNU Affero General Public License v3.0 | 5 votes |
function MenuItem({
to,
externalLink = false,
icon,
iconActive,
label,
onActivate,
}) {
const history = useHistory()
const active = useRouteMatch(to) !== null
const theme = useTheme()
const handlePageRequest = useCallback(() => {
onActivate()
!externalLink ? history.push(to) : window.location.assign(to)
}, [history, onActivate, to, externalLink])
return (
<ButtonBase
onClick={handlePageRequest}
css={`
display: flex;
align-items: center;
margin-top: ${GU * 2}px;
width: 100%;
height: ${5 * GU}px;
padding: 0 ${2 * GU}px 0 ${3 * GU}px;
border-radius: 0;
text-align: left;
background: 'transparent';
`}
>
<div
css={`
position: absolute;
left: 0;
width: 3px;
height: 100%;
opacity: ${Number(active)};
transform: translate3d(${active ? '0%' : '-100%'}, 0, 0);
transform-position: 0 0;
transition-property: transform, opacity;
transition-duration: 150ms;
transition-timing-function: ease-in-out;
`}
/>
<img src={active ? iconActive : icon} alt="" />
<span
css={`
margin-left: ${2 * GU}px;
overflow: hidden;
text-overflow: ellipsis;
${textStyle('body2')};
color: ${active ? '#2C3437' : theme.contentSecondary};
font-weight: ${active ? '700' : '300'};
`}
>
{label}
</span>
</ButtonBase>
)
}