react-router#useLocation TypeScript Examples
The following examples show how to use
react-router#useLocation.
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: Meta.tsx From nosgestesclimat-site with MIT License | 6 votes |
export default function Meta({
title,
description,
image,
url,
children,
}: PropType) {
const { pathname } = useLocation()
return (
<Helmet>
<title>{title} - Nos Gestes Climat</title>
<meta name="description" content={description} />
<meta property="og:type" content="website" />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="twitter:card" content="summary_large_image" />
{/* Attention : og:image does not accept SVG; It must be an absolute URL (https://xxx.png/jpg); */}
{image && <meta property="og:image" content={image} />}
{url && <meta property="og:url" content={url} />}
{children}
</Helmet>
)
}
Example #2
Source File: App.tsx From Riakuto-StartingReact-ja3.1 with Apache License 2.0 | 6 votes |
App: VFC = () => {
const { hash, pathname } = useLocation();
const { action } = useHistory();
useEffect(() => {
if (!hash || action !== 'POP') {
window.scrollTo(0, 0);
}
}, [action, hash, pathname]);
return (
<div className="container">
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/characters" component={Characters} />
<Redirect to="/" />
</Switch>
</div>
);
}
Example #3
Source File: useQueryHandler.ts From backstage with Apache License 2.0 | 6 votes |
export function useQueryHandler() {
const location = useLocation();
function getParsedQuery() {
const { decodedSearch } = getDecodedSearch(location);
const parsedQuery: Partial<Project> = qs.parse(decodedSearch);
return {
parsedQuery,
};
}
function getQueryParamsWithUpdates({
updates,
}: {
updates: {
key: keyof Project;
value: string;
}[];
}) {
const { decodedSearch } = getDecodedSearch(location);
const queryParams = qs.parse(decodedSearch);
for (const { key, value } of updates) {
queryParams[key] = value;
}
return {
queryParams: qs.stringify(queryParams),
};
}
return {
getParsedQuery,
getQueryParamsWithUpdates,
};
}
Example #4
Source File: GroupPanelItem.tsx From tailchat with GNU General Public License v3.0 | 6 votes |
GroupPanelItem: React.FC<{
name: string;
icon: React.ReactNode;
to: string;
badge?: boolean;
}> = React.memo((props) => {
const { icon, name, to, badge } = props;
const location = useLocation();
const isActive = location.pathname.startsWith(to);
return (
<Link className="block" to={to}>
<div
className={clsx(
'w-full hover:bg-black hover:bg-opacity-20 dark:hover:bg-white dark:hover:bg-opacity-20 cursor-pointer text-gray-900 dark:text-white rounded px-1 h-8 flex items-center text-base group',
{
'bg-black bg-opacity-20 dark:bg-white dark:bg-opacity-20': isActive,
}
)}
>
<div className="flex items-center justify-center px-1 mr-1">{icon}</div>
<Typography.Text
className="flex-1 text-gray-900 dark:text-white"
ellipsis={true}
>
{name}
</Typography.Text>
{badge === true ? (
<Badge status="error" />
) : (
<Badge count={Number(badge) || 0} />
)}
</div>
</Link>
);
})
Example #5
Source File: HomeHeaderTabNav.tsx From ledokku with MIT License | 6 votes |
HomeHeaderTabNav = () => {
const location = useLocation();
return (
<Container maxW="5xl">
<TabNav>
<TabNavLink
to="/dashboard"
selected={location.pathname === '/dashboard'}
>
Dashboard
</TabNavLink>
<TabNavLink to="/activity" selected={location.pathname === '/activity'}>
Activity
</TabNavLink>
<TabNavLink to="/metrics" selected={location.pathname === '/metrics'}>
Metrics
</TabNavLink>
<TabNavLink to="/settings" selected={location.pathname === '/settings'}>
Settings
</TabNavLink>
</TabNav>
</Container>
);
}
Example #6
Source File: login.view.tsx From malagu with MIT License | 6 votes |
export function Login() {
const location = useLocation();
const size = useContext(ResponsiveContext);
const intl = useIntl();
const targetUrlParameter = ConfigUtil.get<string>('malagu.security.targetUrlParameter');
const registrations = ConfigUtil.get<{[key: string]: { icon?: string, clientName: string } }>('malagu.oauth2.client.registrations');
const redirect = parse(location.search && location.search.substring(1))[targetUrlParameter];
const queryStr = redirect ? `?${stringify({ [targetUrlParameter]: redirect})}` : '';
return (
<StyledWraper style={size === 'small' ? { top: 0, bottom: 0, right: 0, left: 0 } : undefined }>
<StyledContainer size={size}>
<Box direction="column" pad="large" align="center" background="brand" round={ size === 'small' ? undefined : { corner: 'top', size: '4px' } }>
<Button plain
href={ConfigUtil.get('accounts.home.url')}
icon={<Icon size="large" color="white" icon={ConfigUtil.get('accounts.logo.icon')}></Icon>}>
</Button>
<Heading level="4" color="white">{intl.formatMessage({ id: 'accounts.logo.label' })}</Heading>
</Box>
<Box direction="column" align="center" animation="slideDown">
<Heading level="6">{intl.formatMessage({ id: 'accounts.quick.login.label' })}</Heading>
<Nav>
{
Object.keys(registrations).map(id => (
<Button
hoverIndicator
icon={<Icon icon={registrations[id].icon || registrations[id].clientName} size="large"></Icon>}
href={`/oauth2/authorization/${id}${queryStr}`}>
</Button>
))
}
</Nav>
</Box>
<Box direction="column" fill="horizontal" style={ { position: 'absolute', bottom: 0 } } align="center">
<LocaleMenu size="small" fontSize="12px"/>
</Box>
</StyledContainer>
</StyledWraper>);
}
Example #7
Source File: BetterTradeLink.tsx From cheeseswap-interface with GNU General Public License v3.0 | 6 votes |
export default function BetterTradeLink({ version }: { version: Version }) {
const theme = useContext(ThemeContext)
const location = useLocation()
const search = useParsedQueryString()
const linkDestination = useMemo(() => {
return {
...location,
search: `?${stringify({
...search,
use: version !== DEFAULT_VERSION ? version : undefined
})}`
}
}, [location, search, version])
return (
<YellowCard style={{ marginTop: '12px', padding: '8px 4px' }}>
<AutoColumn gap="sm" justify="center" style={{ alignItems: 'center', textAlign: 'center' }}>
<Text lineHeight="145.23%;" fontSize={16} fontWeight={600} color={theme.colors.text1}>
There is a better price for this trade on{' '}
<StyledInternalLink to={linkDestination}>
<b>Uniswap {version.toUpperCase()} ↗</b>
</StyledInternalLink>
</Text>
</AutoColumn>
</YellowCard>
)
}
Example #8
Source File: Layout.tsx From jobsgowhere with MIT License | 6 votes |
Layout: React.FC<LayoutProps> = function (props) {
const { children } = props;
const auth0Context = React.useContext(Auth0Context);
const location = useLocation<{ pathname: string }>().pathname;
const isActive = location.match(/\/(talents|jobs)\/[a-f0-9-]{36}/);
const { setIsDetailView } = useMobileViewContext();
setIsDetailView(Boolean(isActive));
const profileContext = useProfile();
if (!profileContext?.profile) {
auth0Context?.state?.context?.client?.isAuthenticated().then((res) => {
if (res) profileContext?.refresh();
});
}
return (
<Container>
<Helmet
defaultTitle={process.env.REACT_APP_WEBSITE_NAME}
titleTemplate={`%s | ${process.env.REACT_APP_WEBSITE_NAME}`}
/>
<Header />
{children}
<Footer />
<ToastContainer />
<MessageDialogContainer />
</Container>
);
}
Example #9
Source File: iframeUrlSync.tsx From clearflask with Apache License 2.0 | 6 votes |
IframeBroadcastPathname = (props: {
} & Omit<React.HTMLProps<HTMLIFrameElement>, 'src'>) => {
const location = useLocation();
if (!windowIso.isSsr) {
windowIso.top?.postMessage({
type: 'pathname-changed',
pathname: location.pathname,
title: windowIso.document.title,
}, '*');
}
return null;
}
Example #10
Source File: index.tsx From homebase-app with MIT License | 6 votes |
useStepNumber = (): number => {
const { pathname } = useLocation();
return useMemo(() => {
const extracted: CreatorRouteNames = pathname.endsWith("/")
? pathname.split("/").slice(-2)[0]
: pathname.split("/").slice(-1)[0];
return urlToStepMap[extracted];
}, [pathname]);
}
Example #11
Source File: useQueryParams.ts From one-platform with MIT License | 6 votes |
export default function useQueryParams () {
const [ searchParams, setSearchParams ] = useState<URLSearchParams>(new URLSearchParams());
const location = useLocation();
useEffect( () => {
setSearchParams(new URLSearchParams( location.search ));
}, [ location ] );
return searchParams;
}
Example #12
Source File: utils.ts From nosgestesclimat-site with MIT License | 6 votes |
export function useQuery() {
return new URLSearchParams(useLocation().search)
}
Example #13
Source File: BetterTradeLink.tsx From dyp with Do What The F*ck You Want To Public License | 6 votes |
export default function BetterTradeLink({ version }: { version: Version }) {
const location = useLocation()
const search = useParsedQueryString()
const linkDestination = useMemo(() => {
return {
...location,
search: `?${stringify({
...search,
use: version !== DEFAULT_VERSION ? version : undefined
})}`
}
}, [location, search, version])
return (
<VersionLinkContainer>
There is a better price for this trade on{' '}
<StyledInternalLink to={linkDestination}>
<b>Uniswap {version.toUpperCase()} ↗</b>
</StyledInternalLink>
</VersionLinkContainer>
)
}
Example #14
Source File: EpiComponent.tsx From foundation-lib-spa-core with Apache License 2.0 | 6 votes |
IContentRenderer : React.FunctionComponent<{ data: IContent, contentType?: string, actionName?: string, actionData?: unknown, path?: string }> = (props) =>
{
const context = useEpiserver();
const path = useLocation().pathname;
const componentLoader = useServiceContainer().getService<ComponentLoader>(DefaultServices.ComponentLoader);
const componentName = buildComponentName(props.data, props.contentType);
const [ componentAvailable, setComponentAvailable ] = useState<boolean>(componentLoader.isPreLoaded(componentName));
const debug = context.isDebugActive();
useEffect(() => {
let isCancelled = false;
if (!componentLoader.isPreLoaded(componentName)) {
setComponentAvailable(false);
componentLoader.LoadType(componentName).then(component => {
if (debug) console.debug('IContentRenderer.loadType => Loaded component: ', componentName, component ? 'success' : 'failed', component?.displayName || "Unnamed / no component");
if (!isCancelled) setComponentAvailable(component ? true : false);
});
} else
setComponentAvailable(true);
return () => { isCancelled = true }
}, [componentName, componentLoader, props.data, debug])
if (!componentAvailable)
return <Spinner />
const IContentComponent = componentLoader.getPreLoadedType<ComponentProps<IContent>>(componentName, false);
if (!IContentComponent)
return <Spinner />
if (debug) console.debug('IContentRenderer.render => Component & IContent: ', componentName, props.data);
return <EpiComponentErrorBoundary componentName={ componentName || "Error resolving component" }>
<IContentComponent data={props.data} contentLink={props.data.contentLink} path={path || ''} context={context} actionName={props.actionName} actionData={props.actionData} />
</EpiComponentErrorBoundary>
}
Example #15
Source File: BetterTradeLink.tsx From goose-frontend-amm with GNU General Public License v3.0 | 6 votes |
export default function BetterTradeLink({ version }: { version: Version }) {
const location = useLocation()
const search = useParsedQueryString()
const linkDestination = useMemo(() => {
return {
...location,
search: `?${stringify({
...search,
use: version !== DEFAULT_VERSION ? version : undefined
})}`
}
}, [location, search, version])
return (
<YellowCard style={{ marginTop: '12px', padding: '8px 4px' }}>
<AutoColumn gap="sm" justify="center" style={{ alignItems: 'center', textAlign: 'center' }}>
<Text style={{ lineHeight: '145.23%' }} fontSize="14px">
There is a better price for this trade on{' '}
<StyledInternalLink to={linkDestination}>
<b>Uniswap {version.toUpperCase()} ↗</b>
</StyledInternalLink>
</Text>
</AutoColumn>
</YellowCard>
)
}
Example #16
Source File: Pagination.tsx From Hybooru with MIT License | 6 votes |
export default function Pagination({ count }: PaginationProps) {
const location = useLocation();
const query = qs.parse(location.search);
const page = typeof query.page === "string" && parseInt(query.page) || 0;
const buttons: React.ReactNode[] = [];
const addButton = (target: number | null, text: React.ReactNode) => {
let newSearch;
if(target === null) newSearch = "#";
else newSearch = "?" + qs.stringify({ ...query, page: target });
if(null === target) buttons.push(<span key={buttons.length} className="disabled">{text}</span>);
else buttons.push(<Link key={buttons.length} to={newSearch} className={page === target ? "active" : undefined}>{text}</Link>);
};
addButton(page - 1 < 0 ? null : page - 1, "˂");
for(let i = 0; i < BUTTON_COUNT; i++) {
let midStart = page - Math.round(BUTTON_COUNT / 2) + 2;
if(midStart + BUTTON_COUNT - 1 > count) midStart = count - BUTTON_COUNT + 1;
if(midStart < 1) midStart = 1;
if(i === 0) addButton(i, i + 1); // First Page
else if(i === BUTTON_COUNT - 1 && count > 1) addButton(count - 1, count); // Last Page
else if(i === 1 && midStart > 1) addButton(null, "..."); // Left Ellipsis
else if(i === BUTTON_COUNT - 2 && midStart + BUTTON_COUNT - 1 < count) addButton(null, "..."); // Right Ellipsis
else if(midStart + i < count) addButton(midStart + i - 1, midStart + i); // Middle
}
addButton(page + 1 >= count ? null : page + 1, "˃");
return (
<div className="Pagination">
{buttons}
</div>
);
}
Example #17
Source File: Page1.tsx From glide-frontend with GNU General Public License v3.0 | 6 votes |
PageMeta: React.FC<{ symbol?: string }> = ({ symbol }) => {
const { t } = useTranslation()
const { pathname } = useLocation()
const cakePriceUsd = useCakeUsdcPrice()
const cakePriceUsdDisplay = cakePriceUsd ? `$${cakePriceUsd.toFixed(3)}` : '...'
const pageMeta = getCustomMeta(pathname, t) || {}
const { title, description, image } = { ...DEFAULT_META, ...pageMeta }
let pageTitle = cakePriceUsdDisplay ? [title, cakePriceUsdDisplay].join(' - ') : title
if (symbol) {
pageTitle = [symbol, title].join(' - ')
}
return (
<Helmet>
<title>{pageTitle}</title>
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={image} />
</Helmet>
)
}
Example #18
Source File: BetterTradeLink.tsx From cuiswap with GNU General Public License v3.0 | 6 votes |
export default function BetterTradeLink({ version }: { version: Version }) {
const theme = useContext(ThemeContext)
const location = useLocation()
const search = useParsedQueryString()
const linkDestination = useMemo(() => {
return {
...location,
search: `?${stringify({
...search,
use: version !== DEFAULT_VERSION ? version : undefined
})}`
}
}, [location, search, version])
return (
<YellowCard style={{ marginTop: '12px', padding: '8px 4px' }}>
<AutoColumn gap="sm" justify="center" style={{ alignItems: 'center', textAlign: 'center' }}>
<Text lineHeight="145.23%;" fontSize={14} fontWeight={400} color={theme.text1}>
There is a better price for this trade on{' '}
<StyledInternalLink to={linkDestination}>
<b>Uniswap {version.toUpperCase()} ↗</b>
</StyledInternalLink>
</Text>
</AutoColumn>
</YellowCard>
)
}
Example #19
Source File: terms.tsx From marina with MIT License | 6 votes |
SettingsTerms: React.FC = () => {
const { state } = useLocation<LocationState>();
if (state && state.isFullScreen)
return (
<Shell className="space-y-10">
<h1 className="mb-5 text-3xl font-medium">Terms of Service</h1>
<TermsOfService />;
</Shell>
);
return (
<ShellPopUp
backgroundImagePath="/assets/images/popup/bg-sm.png"
className="h-popupContent container pb-20 mx-auto text-center bg-bottom bg-no-repeat"
currentPage="Terms of Service"
>
<TermsOfService />
</ShellPopUp>
);
}
Example #20
Source File: App.tsx From Riakuto-StartingReact-ja3.1 with Apache License 2.0 | 6 votes |
App: VFC = () => {
const { hash, pathname } = useLocation();
useEffect(() => {
if (!hash) window.scrollTo(0, 0);
}, [hash, pathname]);
return (
<div className="container">
<Routes>
<Route path="/" element={<Home />} />
<Route path="characters" element={<Characters />}>
<Route path="" element={<AllCharacters />} />
<Route path=":schoolCode" element={<SchoolCharacters />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</div>
);
}
Example #21
Source File: index.tsx From taskcafe with MIT License | 6 votes |
UsersConfirm = () => {
const history = useHistory();
const location = useLocation();
const params = QueryString.parse(location.search);
const [hasFailed, setFailed] = useState(false);
const { setUser } = useCurrentUser();
useEffect(() => {
fetch('/auth/confirm', {
method: 'POST',
body: JSON.stringify({
confirmToken: params.confirmToken,
}),
})
.then(async (x) => {
const { status } = x;
if (status === 200) {
const response = await x.json();
const { userID } = response;
setUser(userID);
history.push('/');
} else {
setFailed(true);
}
})
.catch(() => {
setFailed(false);
});
}, []);
return (
<Container>
<LoginWrapper>
<Confirm hasConfirmToken={params.confirmToken !== undefined} hasFailed={hasFailed} />
</LoginWrapper>
</Container>
);
}
Example #22
Source File: BetterTradeLink.tsx From luaswap-interface with GNU General Public License v3.0 | 6 votes |
export function DefaultVersionLink() {
const location = useLocation()
const search = useParsedQueryString()
const version = useToggledVersion()
const linkDestination = useMemo(() => {
return {
...location,
search: `?${stringify({
...search,
use: DEFAULT_VERSION
})}`
}
}, [location, search])
return (
<VersionLinkContainer>
Showing {version.toUpperCase()} price.{' '}
<StyledInternalLink to={linkDestination}>
<b>Switch to LuaSwap {DEFAULT_VERSION.toUpperCase()} ↗</b>
</StyledInternalLink>
</VersionLinkContainer>
)
}
Example #23
Source File: AutoScrollTop.ts From metaflow-ui with Apache License 2.0 | 6 votes |
export default function AutoScrollTop(): null {
const { pathname } = useLocation();
useEffect(() => {
const match = getRouteMatch(pathname);
// Don't use up feature when on task page, there is some scroll handling
if (match && match.params.taskId) {
return;
} else {
window.scrollTo(0, 0);
}
}, [pathname]);
return null;
}
Example #24
Source File: root-router.tsx From shippo with MIT License | 6 votes |
Component: React.FC<RootRouteProps> = ({ result }) => {
const history = useNavigate()
const location = useLocation()
useMount(() => {
console.log(result)
const resource = result[0].data.resource
localStorage.setItem('__PASSPORT', resource.passport)
if (resource.uid > 0) {
message.success(`已经登录,UID为${resource.uid}`)
if (location.pathname.startsWith('/passport')) {
history('/')
}
} else {
message.error('没有登录')
history('/passport')
}
})
return (
<Routes>
<Route path="/passport" element={<Passport />}>
<Route path="" element={<Page_passport />}></Route>
</Route>
<Route path="/dashboard" element={<Home />}>
<Route path="" element={withLoading(lazy(() => import('~/pages/dashboard')))}></Route>
</Route>
<Route path="/read" element={<ReadLayout />}></Route>
<Route path="/creation" element={<CreationLayout />}></Route>
<Route path="*" element={<Navigate to="/dashboard" replace />}></Route>
</Routes>
)
}
Example #25
Source File: Menu.tsx From OpenVolunteerPlatform with MIT License | 6 votes |
Menu: React.FC<MenuProps> = () => {
const location = useLocation();
function renderlistItems(list: Pages[]) {
return list
.filter(route => !!route.path)
.map(p => (
<IonMenuToggle key={p.title} auto-hide="false">
<IonItem detail={false} routerLink={p.path} className={location.pathname.startsWith(p.path) ? 'selected' : undefined}>
<IonIcon slot="start" icon={p.icon} />
<IonLabel>{p.title}</IonLabel>
</IonItem>
</IonMenuToggle>
));
}
return (
<IonMenu type="push" contentId="main">
<IonContent forceOverscroll={false}>
<IonList lines="none">
<IonListHeader>Operations</IonListHeader>
{renderlistItems(routes.operationPages)}
</IonList>
<IonList lines="none">
<IonListHeader>Management</IonListHeader>
{renderlistItems(routes.managementPages)}
</IonList>
</IonContent>
</IonMenu>
);
}
Example #26
Source File: index.tsx From shippo with MIT License | 6 votes |
Home = () => {
const history = useNavigate()
const location = useLocation()
console.log(location)
const [selectedTab, setSelectedTab] = useState(
tabBarItems.find((item) => item.path === location.pathname)!.path
)
const onPress = (activeKey: string) => {
setSelectedTab(activeKey)
const path = tabBarItems.find((item) => item.path === activeKey)?.path
path && history(path)
}
return (
<Container direction="vertical">
<Main>
<Outlet />
</Main>
<Footer height="50px" style={{ backgroundColor: '#fff' }}>
<StyledTabBar activeKey={selectedTab} onChange={(activeKey) => onPress(activeKey)}>
{tabBarItems.map((item) => (
<TabBar.Item title={item.title} key={item.path} icon={<Icon type={item.icon} />} />
))}
</StyledTabBar>
</Footer>
</Container>
)
}
Example #27
Source File: payment-success.tsx From marina with MIT License | 6 votes |
PaymentSuccessView: React.FC<PaymentSuccessProps> = ({ electrsExplorerURL }) => {
const { state } = useLocation<LocationState>();
const history = useHistory();
// Populate ref div with svg animation
const checkmarkLoaderRef = React.useRef(null);
useLottieLoader(checkmarkLoaderRef, '/assets/animations/checkmark.json');
const handleOpenExplorer = () =>
browser.tabs.create({
url: `${electrsExplorerURL}/tx/${state.txid}`,
active: false,
});
const handleBackToHome = () => history.push(DEFAULT_ROUTE);
return (
<ShellPopUp
backgroundImagePath="/assets/images/popup/bg-sm.png"
className="h-popupContent container pb-20 mx-auto text-center bg-bottom bg-no-repeat"
currentPage="Success"
hasBackBtn={false}
>
<h1 className="mt-8 text-lg font-medium">Payment successful !</h1>
<div className="flex items-center justify-center px-20 mt-8" ref={checkmarkLoaderRef} />
<Button className="w-44 container mx-auto mt-10" onClick={handleOpenExplorer} textBase={true}>
See in Explorer
</Button>
<button className="container flex flex-row-reverse mt-24" onClick={handleBackToHome}>
<span className="text-primary text-sm font-bold">Go to Home</span>
<img className="mr-2" src="/assets/images/arrow-narrow-right.svg" alt="navigate home" />
</button>
</ShellPopUp>
);
}
Example #28
Source File: pager.tsx From UsTaxes with GNU Affero General Public License v3.0 | 5 votes |
PagerProvider = <A extends Page>({
children,
pages
}: PropsWithChildren<PagerProviderProps<A>>): ReactElement => {
const lookup = new Map(pages.map((p, i) => [p.url, i]))
const currentLoc = useLocation()
const currentPage = lookup.get(currentLoc.pathname) ?? 0
const navigate = useNavigate()
const onAdvance: (() => void) | undefined = (() => {
if (currentPage < pages.length - 1) {
return () => navigate(pages[currentPage + 1].url)
}
})()
const prev = currentPage > 0 ? pages[currentPage - 1] : undefined
const navButtons: ReactElement = (
<PagerButtons
previousUrl={prev?.url}
submitText={onAdvance !== undefined ? 'Save and Continue' : undefined}
/>
)
return (
<PagerContext.Provider
value={{
onAdvance:
onAdvance ??
(() => {
// end of pages
}),
navButtons
}}
>
{children}
</PagerContext.Provider>
)
}
Example #29
Source File: payment-error.tsx From marina with MIT License | 5 votes |
PaymentError: React.FC = () => {
const history = useHistory();
const { state } = useLocation<LocationState>();
const explorer = useSelector(selectEsploraURL);
const dispatch = useDispatch<ProxyStoreDispatch>();
const handleRetry = async () => {
const txid = await broadcastTx(explorer, state.tx);
if (!txid) throw new Error('something went wrong with the tx broadcasting');
// lock utxos used in successful broadcast
for (const utxo of state.selectedUtxos) {
void dispatch(lockUtxo(utxo));
}
// navigate to payment success page
history.push({
pathname: SEND_PAYMENT_SUCCESS_ROUTE,
state: { txid },
});
};
const handleBackBtn = () => {
history.push({
pathname: SEND_CONFIRMATION_ROUTE,
});
};
return (
<ShellPopUp
backBtnCb={handleBackBtn}
backgroundImagePath="/assets/images/popup/bg-sm.png"
className="h-popupContent container pb-20 mx-auto text-center bg-bottom bg-no-repeat"
currentPage="Error"
>
<h1 className="mt-8 text-lg font-medium">{SOMETHING_WENT_WRONG_ERROR}</h1>
<p className="font-small mt-4 text-sm break-all">{state?.error}</p>
<img className="my-14 mx-auto" src="/assets/images/cross.svg" alt="error" />
{state?.error !== INVALID_PASSWORD_ERROR && (
<Button className="w-36 container mx-auto mt-10" onClick={handleRetry} textBase={true}>
Retry
</Button>
)}
</ShellPopUp>
);
}