next/router#useRouter TypeScript Examples
The following examples show how to use
next/router#useRouter.
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: Buttons.tsx From frames with Mozilla Public License 2.0 | 7 votes |
BackButton = ({response}: { response: { mediaId: number, episodeName: string | null, logo: string | null, name: string } }) => {
const router = useRouter();
const {disconnect} = useGroupWatch();
const routeOut = async (ev: any) => {
ev.stopPropagation();
await disconnect();
const url = '/' + (response.episodeName ? 'show' : 'movie') + '=' + response.name.replace(/\s/g, '+');
document.body.removeAttribute('style');
await router.push('/info?mediaId=' + response.mediaId, url);
await mutate('/api/load/continue');
}
return (
<svg className={styles.bb} viewBox="0 0 512 512" onClick={routeOut}>
<path d="M256,0C114.844,0,0,114.844,0,256s114.844,256,256,256s256-114.844,256-256S397.156,0,256,0z M256,490.667
C126.604,490.667,21.333,385.396,21.333,256S126.604,21.333,256,21.333S490.667,126.604,490.667,256S385.396,490.667,256,490.667
z"/>
<path d="M394.667,245.333H143.083l77.792-77.792c4.167-4.167,4.167-10.917,0-15.083c-4.167-4.167-10.917-4.167-15.083,0l-96,96
c-4.167,4.167-4.167,10.917,0,15.083l96,96c2.083,2.083,4.813,3.125,7.542,3.125c2.729,0,5.458-1.042,7.542-3.125
c4.167-4.167,4.167-10.917,0-15.083l-77.792-77.792h251.583c5.896,0,10.667-4.771,10.667-10.667S400.563,245.333,394.667,245.333
z"/>
</svg>
)
}
Example #2
Source File: index.tsx From tams-club-cal with MIT License | 7 votes |
Auth = ({ token, error }: InferGetServerSidePropsType<typeof getServerSideProps>) => {
const router = useRouter();
// When loaded, check if the user has a token parameter in the url
// If they do, return the user to the previous page they were on
// Otherwise, redirect them to the home page and show an error
useEffect(() => {
if (error) {
setTimeout(() => {
router.push('/profile');
}, 3000);
} else {
// Saves the token into the cookies so the user doesn't have to re-login
// TODO: This does not seem to work for long TT-TT
const cookies = new Cookies();
cookies.set('token', token, { sameSite: 'strict', path: '/' });
// Return the user to the previous page they were on
const prev = cookies.get('prev');
cookies.remove('prev', { path: '/' });
if (prev) router.push(prev);
else router.push('/profile/dashboard');
}
}, []);
return (
<PageWrapper>
<TitleMeta title="Authenticating" path="/auth" />
<RobotBlockMeta />
<Loading error={error}>
Error logging in. Please check your internet and allow cookies then try again. Redirecting you to the
login page in 3 seconds...
</Loading>
</PageWrapper>
);
}
Example #3
Source File: SearchBox.tsx From posso-uscire with GNU General Public License v3.0 | 7 votes |
export default function SearchBox() {
const [language] = useLanguage();
const router = useRouter();
return (
<Box display="flex" justifyContent="center">
<Autocomplete
id="province"
onChange={(_, value) => router.push("/" + (value as Province).urlName)}
options={regions}
getOptionLabel={(option) => option.nome}
style={{ width: "80%", marginTop: 20 }}
renderInput={(params) => (
<TextField
{...params}
label={i18n.CITY[language]}
variant="outlined"
/>
)}
/>
</Box>
);
}
Example #4
Source File: _app.tsx From 35d-blog with MIT License | 6 votes |
App = ({ Component, pageProps }) => {
const router = useRouter()
let defaultTheme
if (process.browser) {
defaultTheme = window.localStorage.getItem('35d_theme') || 'LIGHT'
}
const [theme, setTheme] = useState(defaultTheme)
const toggleDarkMode = () => {
if (process.browser) {
window.localStorage.setItem('35d_theme', theme === 'LIGHT' ? 'DARK' : 'LIGHT')
}
theme === 'LIGHT' ? setTheme('DARK') : setTheme('LIGHT')
}
return (
<ThemeProvider theme={theme === 'LIGHT' ? lightTheme : darkTheme}>
<>
<DarkModeContext.Provider value={{ theme, toggleDarkMode }}>
<div className="w-full max-w-3xl mx-auto flex flex-wrap items-start overflow-hidden">
<Navigation />
<main className="w-full sm:w-3/4 ml-0 sm:ml-1/4 min-h-screen">
<Breadcrumbs route={router.route} />
<Component {...pageProps} className="w-full sm:w-3/4 sm:-mt-1 ml-0 sm:ml-1/4" />
</main>
<Footer />
</div>
</DarkModeContext.Provider>
</>
</ThemeProvider>
)
}
Example #5
Source File: NavigationDrawer.tsx From next-saas-starter with MIT License | 6 votes |
function NavItemsList({ items }: NavigationDrawerProps) {
const { close } = OriginalDrawer.useDrawer()
const router = useRouter()
useEffect(() => {
function handleRouteChangeComplete() {
close()
}
router.events.on('routeChangeComplete', handleRouteChangeComplete)
return () => router.events.off('routeChangeComplete', handleRouteChangeComplete)
}, [close, router])
return (
<ul>
{items.map((singleItem, idx) => {
return (
<NavItem key={idx}>
<NextLink href={singleItem.href}>{singleItem.title}</NextLink>
</NavItem>
)
})}
</ul>
)
}
Example #6
Source File: [handle].tsx From nextjs-shopify with MIT License | 6 votes |
export default function Handle({
collection,
page,
}: InferGetStaticPropsType<typeof getStaticProps>) {
const router = useRouter()
const isLive = !Builder.isEditing && !Builder.isPreviewing
const { theme } = useThemeUI()
if (!collection && isLive) {
return (
<>
<Head>
<meta name="robots" content="noindex" />
<meta name="title"></meta>
</Head>
<DefaultErrorPage statusCode={404} />
</>
)
}
return router.isFallback && isLive ? (
<h1>Loading...</h1> // TODO (BC) Add Skeleton Views
) : (
<BuilderComponent
isStatic
key={collection.id}
model={builderModel}
data={{ collection, theme }}
{...(page && { content: page })}
/>
)
}
Example #7
Source File: Layout.tsx From Cromwell with MIT License | 6 votes |
export default function Layout(props: TProps | undefined) {
const router = useRouter?.();
useEffect(() => {
appState.closeAllModals();
}, [router?.asPath]);
return (
<div className={styles.Layout}>
<Header />
<CartModal />
<WishlistModal />
<ViewedModal />
<ProductQuickView />
<SignInModal />
<div className={styles.main}>
{props?.children}
</div>
<Footer />
</div>
)
}
Example #8
Source File: season.tsx From frames with Mozilla Public License 2.0 | 6 votes |
export default function Element(item: SpringEpisode) {
const setSection = useSetRecoilState(InfoSectionContext);
const {backdrop, id, name, overview, show, position, type} = item;
const router = useRouter();
return (
<li onClick={async () => {
if (type === 'SEASON')
setSection(name);
else await router.push('/watch?episodeId=' + id);
}}>
<div className={styles.d}>
<img src={backdrop ? backdrop: type === 'EPISODE' ? show.backdrop: show.poster} alt={name}/>
<div style={position && position > 0 ? {display: "block"} : {}} className={styles.e}>
<div className={styles.fill} style={{width: position + '%'}}/>
</div>
<div className={styles.c}>{name}</div>
{overview ? <p>{overview}</p> : null}
</div>
</li>
);
}
Example #9
Source File: AuthRedirect.tsx From frontend.ro with MIT License | 6 votes |
function AuthRedirect() {
const router = useRouter();
const onLogin = (user: UserState['info']) => {
const nextHref = router.query.next as string;
router.replace(nextHref || `/${user.username}`);
};
return (
<PageContainer className={styles.main}>
<h2>
<span>Pentru a continua, autentifică-te ?</span>
</h2>
<div>
<Login className={styles.login} onSuccess={onLogin} />
</div>
</PageContainer>
);
}
Example #10
Source File: RedirectIfUser.tsx From pagely with MIT License | 6 votes |
RedirectIfUser = () => {
const router = useRouter();
const { user } = useClerk();
useEffect(() => {
router.prefetch('/dashboard');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (user) {
router.push('/dashboard');
}
return <></>;
}
Example #11
Source File: Head.tsx From BloggerWeb with GNU General Public License v3.0 | 6 votes |
Head = ({ customMeta }: { customMeta?: MetaProps }): JSX.Element => {
const router = useRouter();
const meta: MetaProps = {
title: 'Hunter Chang - Website',
description:
'Sleep Deprived Father. Senior Web Developer. Lover of all things Ramen and Kpop.',
image: `${WEBSITE_HOST_URL}/images/site-preview.png`,
type: 'website',
...customMeta,
};
return (
<NextHead>
<title>{meta.title}</title>
<meta content={meta.description} name="description" />
<meta property="og:url" content={`${WEBSITE_HOST_URL}${router.asPath}`} />
<link rel="canonical" href={`${WEBSITE_HOST_URL}${router.asPath}`} />
<meta property="og:type" content={meta.type} />
<meta property="og:site_name" content="Hunter Chang - Website" />
<meta property="og:description" content={meta.description} />
<meta property="og:title" content={meta.title} />
<meta property="og:image" content={meta.image} />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@huntarosan" />
<meta name="twitter:title" content={meta.title} />
<meta name="twitter:description" content={meta.description} />
<meta name="twitter:image" content={meta.image} />
{meta.date && (
<meta property="article:published_time" content={meta.date} />
)}
</NextHead>
);
}
Example #12
Source File: [carId].tsx From master-frontend-lemoncode with MIT License | 6 votes |
CarPage = () => {
const router = useRouter();
return (
<>
<Head>
<title>Rent a car - Car {router.query.carId} details</title>
</Head>
<h2>Car detail page</h2>
<p>{router.query.carId}</p>
</>
);
}
Example #13
Source File: Link.tsx From tams-club-cal with MIT License | 6 votes |
Link = React.forwardRef<HTMLAnchorElement, LinkProps>(function Link(props, ref) {
const {
activeClassName = 'active',
as: linkAs,
className: classNameProps,
href,
noLinkStyle,
role, // Link don't have roles.
...other
} = props;
const router = useRouter();
const pathname = typeof href === 'string' ? href : href.pathname;
const className = clsx(classNameProps, {
[activeClassName]: router.pathname === pathname && activeClassName,
});
const isExternal = typeof href === 'string' && (href.indexOf('http') === 0 || href.indexOf('mailto:') === 0);
if (isExternal) {
if (noLinkStyle) {
return <Anchor className={className} href={href} ref={ref} {...other} />;
}
return <MuiLink className={className} href={href} ref={ref} {...other} />;
}
if (noLinkStyle) {
return <NextLinkComposed className={className} ref={ref} to={href} {...other} />;
}
return (
<MuiLink component={NextLinkComposed} linkAs={linkAs} className={className} ref={ref} to={href} {...other} />
);
})
Example #14
Source File: 404.tsx From website with MIT License | 6 votes |
export default function NotFound() {
const router = useRouter();
return (
<Container>
<Header>404 - Page not found</Header>
<Paragraph>
The requested page <Bold>{router.asPath}</Bold> couldn' be found.{' '}
<Link href="/">Go home?</Link>
</Paragraph>
</Container>
);
}
Example #15
Source File: SwitchToChain.tsx From hypertext with GNU General Public License v3.0 | 6 votes |
export default function SwitchToChain({ requiredChainId }: { requiredChainId: number }): JSX.Element {
const { pathname, push } = useRouter()
return (
<Flex flexGrow={1} alignItems="center" justifyContent="center">
<Stack direction="column" alignItems="center">
<Text fontSize="1.5rem">
Please connect to the {requiredChainId === 1 ? 'Ethereum' : ''} {CHAIN_ID_NAMES[requiredChainId]}
{requiredChainId !== 1 ? ' testnet' : ''}.
</Text>
<Button
width="min-content"
onClick={(): void => {
if (isIPFS) {
window.location.assign(`.${pathname}.html`)
} else {
push(pathname, undefined, { shallow: true })
}
}}
>
Here by mistake?
</Button>
</Stack>
</Flex>
)
}
Example #16
Source File: Breadcrumbs.tsx From crowdsource-dataplatform with MIT License | 6 votes |
Breadcrumbs = ({ initiative, path }: BreadcrumbsPorpsInterface) => {
const { t } = useTranslation();
const { locale: currentLocale } = useRouter();
const language = isLanguageImageAvailable(currentLocale);
const initiativeName = `${t(initiative)} ${t('initiativeTextSuffix')}`;
return (
<div className={`${styles.root} d-flex align-items-center`} data-testid="Breadcrumbs">
<Link href={routePaths[`${initiative}InitiativeHome`]}>
<a className={styles.link}>
<div className="d-flex align-items-center cursor-pointer">
<div className={`${styles.icon} d-flex`}>
<ImageBasePath
src={`/images/${nodeConfig.brand}/${language}/logos/${language}-${INITIATIVES_MAPPING[initiative]}InitiativeLogo.svg`}
alt={t(`${initiative}Logo`)}
width="47"
height="42"
/>
</div>
<span className={`${styles.initiative} d-none d-md-block ms-1 ms-md-3 font-family-rowdies`}>
{initiativeName}
</span>
</div>
</a>
</Link>
<span className="mx-1 mx-md-3 text-primary-40">/</span>
<span className="display-5">{t(path)}</span>
</div>
);
}
Example #17
Source File: index.tsx From RareCamp with Apache License 2.0 | 6 votes |
AccountMenu = () => {
const router = useRouter()
const mutation = useMutation(() => Auth.signOut({ global: true }), {
onSuccess: router.reload,
onError: (err: Error) =>
notification.error({
message: 'Can not logout',
description: err.message,
placement: 'topRight',
duration: 1.5,
}),
})
return (
<OFMenu>
<Menu.Item>
<Link href="/auth/password">Update Password</Link>
</Menu.Item>
<Menu.Item>
<Button
loading={mutation.isLoading}
onClick={() => mutation.mutate()}
>
Logout
</Button>
</Menu.Item>
</OFMenu>
)
}
Example #18
Source File: AboutName.tsx From mkn with MIT License | 6 votes |
AboutName: React.FC<IProps> = (props) => {
useDarkMode();
const { name } = useRouter()?.query;
return (
<PageWrapper
className={cx(
styles['comp-wrapper'],
{ [styles['comp-wrapper--alwaysDarkMode']]: props.alwaysDarkMode },
`g-comp--${AboutName.displayName}`,
props.className,
)}
style={props.style}
>
<HtmlMeta title={`${name}`} />
<HugeIcon icon={<FiMoon />} className={styles['huge-icon']} />
<div className={styles['params-info']}>
<code>{name}</code>
</div>
</PageWrapper>
);
}
Example #19
Source File: PermalinkHandler.ts From Teyvat.moe with GNU General Public License v3.0 | 6 votes |
PermalinkHandler: FunctionComponent = () => {
const nextRouter = useRouter();
// Navigate to the marked permalink when the map starts.
useEffect(() => {
const { id } = nextRouter.query;
// End early if 0 or 2+ IDs were specified.
if (id == null || _.isArray(id)) return;
dispatchSetPermalinkId(id);
}, [nextRouter.query]);
// Don't render anything.
return null;
}
Example #20
Source File: index.tsx From thvu-blog with MIT License | 6 votes |
export default function LoginButton({ provider }: { provider: ClientSafeProvider }) {
const [isDark, mounted] = useDarkTheme();
const { Logo, LogoDark, bg, bgDark, text, textDark } = providerStyleGuides[provider.id];
const router = useRouter();
const { callbackUrl } = router.query;
if (!mounted) return null;
return (
<div key={provider.name}>
<button
className={`w-56 h-12 flex items-center gap-3 text-sm font-medium leading-5 transition-colors duration-150 border border-transparent rounded-lg shadow focus:outline-none focus:shadow-outline-primary
${isDark && bgDark ? bgDark : bg}
${isDark && textDark ? textDark : text} `}
onClick={() => signIn(provider.id, { callbackUrl: callbackUrl as string })}
>
{isDark && LogoDark ? <LogoDark className="h-full p-2" /> : <Logo className="h-full p-2" />}
Sign in with {provider.name}
</button>
</div>
);
}
Example #21
Source File: index.tsx From posso-uscire with GNU General Public License v3.0 | 6 votes |
Index: React.FC<{ buildTime: number }> = ({ buildTime }) => {
const router = useRouter();
urlUtils.hashConsumer((province) => router.push("/" + province));
return (
<Layout buildTime={buildTime}>
<SearchBox />
</Layout>
);
}
Example #22
Source File: profile.tsx From telegram-standup-bot with MIT License | 6 votes |
ProfilePage = () => {
const router = useRouter();
const { user } = router.query;
return (
<>
<main className={styles.main}>{user}</main>
</>
);
}
Example #23
Source File: ProductJSON.tsx From storefront with MIT License | 6 votes |
ProductJSON: React.VFC<Props> = ({ product }) => {
const router = useRouter();
const { settings } = useSettings();
return (
<ProductJsonLd
productName={product?.name ?? ''}
images={
[
product?.image?.sourceUrl,
...(product?.galleryImages?.nodes?.map((mediaItem) => mediaItem?.sourceUrl) ?? []),
].filter((sourceUrl) => sourceUrl != null) as string[]
}
description={product?.seo?.metaDesc ?? ''}
offers={
product?.__typename === 'SimpleProduct'
? {
price: product.price ?? '0',
priceCurrency: 'EUR',
itemCondition: 'https://schema.org/NewCondition',
availability:
product.stockStatus === StockStatusEnum.OUT_OF_STOCK
? 'http://schema.org/OutOfStock'
: product.stockStatus === StockStatusEnum.IN_STOCK
? 'http://schema.org/InStock'
: product.stockStatus === StockStatusEnum.ON_BACKORDER
? 'http://schema.org/PreOrder'
: undefined,
url: absoluteURL(router.asPath),
seller: {
name: settings.title,
},
}
: undefined
}
/>
);
}
Example #24
Source File: index.tsx From merkle-airdrop-starter with GNU Affero General Public License v3.0 | 5 votes |
export default function Home() {
// Routing
const { push } = useRouter();
// Authentication status
const { address }: { address: string | null } = eth.useContainer();
return (
<Layout>
<div className={styles.home}>
{/* Project logo */}
<div>
<Image src="/logo.png" alt="Logo" width={250} height={250} priority />
</div>
{/* Project introduction article, if it exists */}
{process.env.NEXT_PUBLIC_ARTICLE ? (
<a
href={process.env.NEXT_PUBLIC_ARTICLE}
target="_blank"
rel="noopener noreferrer"
>
Introducing {tokenName}{" "}
<Image src="/icons/arrow.svg" alt="Arrow" height={12} width={12} />
</a>
) : null}
{/* Project heading */}
<h1>{heading}</h1>
{/* Project description */}
<p>{description}</p>
{/* Claim button */}
{!address ? (
// If not authenticated, disabled
<button disabled>Connect Wallet to Claim Tokens</button>
) : (
// Else, reroute to /claim
<button onClick={() => push("/claim")}>Claim Tokens</button>
)}
</div>
</Layout>
);
}
Example #25
Source File: Navbar.tsx From next-saas-starter with MIT License | 5 votes |
export default function Navbar({ items }: NavbarProps) {
const router = useRouter();
const { toggle } = Drawer.useDrawer();
const [scrollingDirection, setScrollingDirection] = useState<ScrollingDirections>('none');
let lastScrollY = useRef(0);
const lastRoute = useRef('');
const stepSize = useRef(50);
useScrollPosition(scrollPositionCallback, [router.asPath], undefined, undefined, 50);
function scrollPositionCallback({ currPos }: ScrollPositionEffectProps) {
const routerPath = router.asPath;
const hasRouteChanged = routerPath !== lastRoute.current;
if (hasRouteChanged) {
lastRoute.current = routerPath;
setScrollingDirection('none');
return;
}
const currentScrollY = currPos.y;
const isScrollingUp = currentScrollY > lastScrollY.current;
const scrollDifference = Math.abs(lastScrollY.current - currentScrollY);
const hasScrolledWholeStep = scrollDifference >= stepSize.current;
const isInNonCollapsibleArea = lastScrollY.current > -50;
if (isInNonCollapsibleArea) {
setScrollingDirection('none');
lastScrollY.current = currentScrollY;
return;
}
if (!hasScrolledWholeStep) {
lastScrollY.current = currentScrollY;
return;
}
setScrollingDirection(isScrollingUp ? 'up' : 'down');
lastScrollY.current = currentScrollY;
}
const isNavbarHidden = scrollingDirection === 'down';
const isTransparent = scrollingDirection === 'none';
return (
<NavbarContainer hidden={isNavbarHidden} transparent={isTransparent}>
<Content>
<NextLink href="/" passHref>
<LogoWrapper>
<Logo />
</LogoWrapper>
</NextLink>
<NavItemList>
{items.map((singleItem) => (
<NavItem key={singleItem.href} {...singleItem} />
))}
</NavItemList>
<ColorSwitcherContainer>
<ColorSwitcher />
</ColorSwitcherContainer>
<HamburgerMenuWrapper>
<HamburgerIcon aria-label="Toggle menu" onClick={toggle} />
</HamburgerMenuWrapper>
</Content>
</NavbarContainer>
);
}
Example #26
Source File: Searchbar.tsx From nextjs-shopify with MIT License | 5 votes |
Searchbar: FC<Props> = () => {
const router = useRouter()
const { q } = router.query
const [isOpen, setIsOpen] = useState(false)
const buttonRef = useRef<HTMLDivElement>(null)
useEffect(() => {
setIsOpen(false)
}, [router.asPath.split('?')[0]])
return (
<React.Fragment>
<ExpandModal
transitionConfig={{}}
contentTransition={{}}
overlayProps={{
style: {
maxWidth: 1920,
left: '50%',
transform: 'translateX(-50%)',
overflow: 'auto',
top: (buttonRef.current?.getBoundingClientRect().bottom || 0) + 15,
},
}}
isOpen={isOpen}
>
<SearchModalContent
initialSearch={q && String(q)}
onSearch={(term: string) => {
const op = q ? 'replace' : 'push'
router[op]({
pathname: router.asPath.split('?')[0],
query: {
q: term,
},
})
}}
/>
</ExpandModal>
<Themed.div
ref={buttonRef}
as={Button}
mx={2}
onClick={() => setIsOpen(!isOpen)}
aria-label="Search"
>
{isOpen ? (
<Cross />
) : (
<svg
width="20"
height="22"
viewBox="0 0 20 22"
fill="none"
stroke="currentColor"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
/>
</svg>
)}
</Themed.div>
</React.Fragment>
)
}
Example #27
Source File: [slug].tsx From Cromwell with MIT License | 5 votes |
BlogPostPage: TPageWithLayout<BlogPostProps> = (props) => {
const { post } = props;
const router = useRouter?.();
if (post && !post.pageTitle) {
// Default meta page title
post.pageTitle = post.title;
}
return (
<CContainer className={styles.BlogPost} id="post_01">
<EntityHead
entity={post}
useFallback
/>
<CContainer className={commonStyles.content} id="post_02">
{post?.mainImage && (
<img className={styles.mainImage} src={post.mainImage} />
)}
</CContainer>
<CContainer className={styles.postContent} id="post_03">
{(!post && router && router.isFallback) && (
<LoadBox />
)}
{(!post && !(router && router.isFallback)) && (
<div className={styles.notFound}>
<h3>Post not found</h3>
</div>
)}
{post?.title && (
<h1 className={styles.postTitle}>{post?.title}</h1>
)}
{post?.tags && (
<div className={postStyles.tagsBlock}>
{post?.tags?.map(tag => {
return (
<Link href={`/tag/${tag.slug}`}
key={tag.id}
className={postStyles.tag}
>{tag?.name}</Link>
)
})}
</div>
)}
{post && (
<div className={styles.postInfo}>
<PostInfo data={post} />
</div>
)}
{post?.content && (
<div id="text-editor" dangerouslySetInnerHTML={{
__html: post?.content
}}></div>
)}
</CContainer>
</CContainer>
);
}
Example #28
Source File: navbar.tsx From frames with Mozilla Public License 2.0 | 5 votes |
export function AccountInfo() {
const count = useRecoilValue(notificationCount);
const setSides = useSetRecoilState(SettingsSegmentContext);
const accountContext = useRecoilValue(SideMenu);
const [visible, setVisible] = useState(false);
const router = useRouter();
const {user, signOut} = useUser();
const win = useRef<Window | null>(null);
const handleClick = () => {
win.current = window.open('https://www.paypal.com/paypalme/RoyOssai', '_blank');
}
const setSidesAndPush = async (step1: string, step2: string) => {
setSides({step1, step2});
router.asPath !== '/settings' && await router.push('/settings');
}
if (user)
return (
<div className={styles.holderContainer}
style={accountContext === 0 && !visible ? {opacity: "0", pointerEvents: 'none'} : {opacity: "1"}}
onMouseEnter={() => setVisible(true)} onMouseLeave={() => {
setTimeout(() => {
setVisible(false);
}, 200)
}}>
<div className={styles.text} onClick={() => setSidesAndPush('account', 'watch history')}>{user.role === Role.GUEST ? 'Guest: ': ''}{user.username || user.email}</div>
<div className={styles.spacer}/>
<div className={styles.text} onClick={() => setSidesAndPush('account', 'notifications')}>Notifications{count ? `: ${count}`: ''}</div>
<div className={styles.text} onClick={() => setSidesAndPush('about', 'feedback')}>Make Suggestions</div>
<div className={styles.text} onClick={handleClick}>Buy me coffee</div>
<div className={styles.text} onClick={() => setSidesAndPush('about', 'privacy policy')}>Privacy & TOS</div>
{user.role === Role.ADMIN ?
<>
<div className={styles.spacer}/>
<div className={styles.text} onClick={() => setSidesAndPush('manage', 'get contents')}>Manage contents</div>
</>
: null}
<div className={styles.spacer}/>
<div className={styles.text} onClick={signOut}>log out</div>
</div>
)
else return null;
}
Example #29
Source File: AccountTooltip.tsx From frontend.ro with MIT License | 5 votes |
function AccountTooltip({ theme = 'default', user, dispatch }: Props & ConnectedProps<typeof connector>) {
const ref = useRef(null);
const router = useRouter();
const [isOpen, setIsOpen] = useState(false);
const logout = () => {
UserService.logout().then(() => {
router.replace('/').then(() => {
dispatch(logoutUser());
});
});
};
const toggleToolip = () => setIsOpen(!isOpen);
useOutsideClick(ref, () => setIsOpen(false));
return (
<div ref={ref} className={`${styles['account-tooltip']} ${styles[`theme-${theme}`]}`}>
<Button className={styles.avatar} onClick={toggleToolip}>
<img
className="pointer"
title="Toggle menu"
src={user.info.avatar}
alt={`${user.info.name} avatar`}
width="32"
data-toggle="true"
/>
</Button>
{isOpen && (
<List className="menu">
<li>
<Link href={`/${user.info.username}`}>
<a className="no-underline">
Profilul tău
</a>
</Link>
</li>
<li>
<Link href="/settings">
<a className="no-underline">
Setările contului
</a>
</Link>
</li>
<li>
<a href="#" onClick={logout} className="no-underline">
Sign out
</a>
</li>
</List>
)}
</div>
);
}