gatsby#navigate JavaScript Examples
The following examples show how to use
gatsby#navigate.
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: category-template.js From zoomkoding-gatsby-blog with BSD Zero Clause License | 6 votes |
function CategoryTemplate({ pageContext }) {
const { edges, currentCategory } = pageContext;
const { categories } = pageContext;
const currentTabIndex = useMemo(
() => categories.findIndex((category) => category === currentCategory),
[categories, currentCategory],
);
const posts = edges.map(({ node }) => new Post(node));
const onTabIndexChange = useCallback(
(e, value) => {
if (value === 0) return navigate(`/posts`);
navigate(`/posts/${categories[value]}`);
},
[categories],
);
return (
<Layout>
<Seo title="Posts" />
<CategoryPageHeader title={categories[currentTabIndex]} subtitle={`${posts.length} posts`} />
<PostTabs
tabIndex={currentTabIndex}
onChange={onTabIndexChange}
tabs={categories}
posts={posts}
/>
</Layout>
);
}
Example #2
Source File: Center.js From jamstack-ecommerce with MIT License | 6 votes |
Center = ({ price, title, link }) => {
function navigateTo() {
navigate(link)
}
return (
<div>
<p className="text-4xl xl:text-5xl font-bold tracking-widest leading-none">{title}</p>
<p>FROM <span>${price}</span></p>
<Button
onClick={navigateTo}
title="Shop Now"
/>
</div>
)
}
Example #3
Source File: MuktiLogo.jsx From test-deploy-gatsby-apps with BSD Zero Clause License | 6 votes |
MuktiLogo = () => {
const classes = useStyles()
return (
<IconButton
disableFocusRipple
disableRipple
className={classes.iconButton}
onClick={() => navigate("/")}
>
<img src={logo} className={classes.logo} alt={"logo"} />
</IconButton>
)
}
Example #4
Source File: Root.js From testnets-cardano-org with MIT License | 6 votes |
AdminRedirector = ({ hash }) => {
function adminRedirect () {
const hashParams = hash.replace(/^#\/?/, '').split('&').map(p => p.split('='))
const tokenParams = [ 'invite_token', 'access_token' ]
const hasToken = hashParams.filter(p => tokenParams.includes(p[0])).length > 0
if (hasToken) {
analytics.autoCapture({ category: analytics.constants.REDIRECT, action: 'redirect_to_admin' })
navigate(`/admin/${hash}`)
}
}
useEffect(() => {
adminRedirect()
}, [])
return null
}
Example #5
Source File: template.js From firecamp-doc with MIT License | 6 votes |
function CustomLink(props) {
const {pathPrefix, baseUrl} = useContext(CustomLinkContext);
const linkProps = {...props};
if (props.href) {
if (props.href.startsWith('/')) {
linkProps.onClick = function handleClick(event) {
const href = event.target.getAttribute('href');
if (href.startsWith('/')) {
event.preventDefault();
navigate(href.replace(pathPrefix, ''));
}
};
} else if (!props.href.startsWith('#') && !props.href.startsWith(baseUrl)) {
linkProps.target = '_blank';
linkProps.rel = 'noopener noreferrer';
}
}
return <a {...linkProps} />;
}
Example #6
Source File: Bag.test.js From ecommerce with MIT License | 6 votes |
test('should display message and button directing to the store when bag is empty', () => {
const { getByText } = render(tree);
expect(getByText("Looks like there's nothing in your bag.")).toBeInTheDocument();
fireEvent.click(getByText('Start shopping'));
expect(navigate).toHaveBeenCalledTimes(1);
expect(navigate).toHaveBeenCalledWith('/');
});
Example #7
Source File: 404.js From mds-docs with MIT License | 6 votes |
PageNotFound = () => {
return (
<Homepage relativePagePath={'/404'} is404={true}>
<div className='m-auto w-50 mt-10'>
<Heading size='xl'>Page not found</Heading>
<Paragraph className='my-8'>
Oops! The page you are looking for has been
removed or relocated.
</Paragraph>
<Button
icon='arrow_backward'
iconAlign='left'
onClick={() => navigate(-1)}
>
Go Back
</Button>
</div>
</Homepage>
);
}
Example #8
Source File: ProtectedRoute.js From TalkTrack with MIT License | 6 votes |
export default function ProtectedRoute({ children }) {
const { loading, isAuthenticated } = useAuth0();
if (loading) return <p>Loading...</p>;
const isBrowser = typeof window !== 'undefined';
if (!isAuthenticated && isBrowser) {
navigate('/');
}
return { ...children };
}
Example #9
Source File: PrivateRoute.js From gatsby-apollo-wpgraphql-jwt-starter with MIT License | 6 votes |
PrivateRoute = ({ component: Component, location, ...rest }) => {
const auth = useAuth()
if (!auth.isLoggedIn() && isBrowser && window.location.pathname !== `/login/`) {
navigate(`/dashboard/login/`, {replace: true})
return null
}
return <Component {...rest} />
}
Example #10
Source File: template.js From guitar-book with MIT License | 6 votes |
function CustomLink(props) {
const {pathPrefix, baseUrl} = useContext(CustomLinkContext);
const linkProps = {...props};
if (props.href) {
if (props.href.startsWith('/')) {
linkProps.onClick = function handleClick(event) {
const href = event.target.getAttribute('href');
if (href.startsWith('/')) {
event.preventDefault();
navigate(href.replace(pathPrefix, ''));
}
};
} else if (!props.href.startsWith('#') && !props.href.startsWith(baseUrl)) {
linkProps.target = '_blank';
linkProps.rel = 'noopener noreferrer';
}
}
return <a {...linkProps} />;
}
Example #11
Source File: use-form.js From phirannodesigns-coding-challenge with MIT License | 6 votes |
export function useForm(initialState) {
function encode(data) {
return Object.keys(data)
.map(
(key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`
)
.join('&');
}
const [state, setState] = useState(initialState);
function handleChange(e) {
setState({ ...state, [e.target.name]: e.target.value });
}
function handleSubmit(e) {
e.preventDefault();
const form = e.target;
fetch('/', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: encode({
'form-name': form.getAttribute('name'),
...state,
}),
})
.then(() => navigate(form.getAttribute('action')))
.catch((error) => alert(error));
}
return { handleSubmit, handleChange, state };
}
Example #12
Source File: admin.js From website with BSD Zero Clause License | 6 votes |
export default function Admin({ location }) {
const [usuario] = useState(obtUsuarioStorage());
// Índice
const [indPestanaActiva, estIndPestanaActiva] = useState(0);
if (!usuario) {
navigate('/login');
}
return (
<div>
<Navbar currentPage={location.pathname} />
<div className="contenedor cuerpo-pagina">
<h2 className="titulo-seccion mt-5">Hola admin</h2>
<Pestanas cargando={false} indice={indPestanaActiva} seleccionar={estIndPestanaActiva} data={['Profesores', 'Cursos']}>
<TablaDocentes />
<TablaCursos />
</Pestanas>
</div>
<Footer />
</div>
)
}
Example #13
Source File: header.jsx From openlawnz-website with GNU General Public License v3.0 | 6 votes |
Header = () => {
const [ query, setQuery ] = useState('')
return (
<header>
<div className="inner">
<div>
<Link to="/"><img src={Logo} alt="OpenLaw NZ logo" /></Link>
</div>
<nav>
<Link to="/our-mission" activeClassName="active">Our Mission</Link>
<Link to="/how-to-use" activeClassName="active">How to Use</Link>
<Link to="/news" activeClassName="active">News</Link>
</nav>
<form method="get" onSubmit={(e) => {
e.preventDefault()
navigate(`/search?q=${query}`)
}}>
<div id="search-simple">
<label className="show-for-sr" htmlFor="top-search">Search 30k cases</label>
<input type="search" placeholder="Search 30k cases" name="q" id="top-search" value={query} onChange={e => setQuery(e.target.value)} required />
<button type="submit">
Search
</button>
</div>
<div id="search-options">
<Link to="/search">Advanced Search</Link>
</div>
</form>
</div>
</header>
)
}
Example #14
Source File: index.js From zoomkoding-gatsby-blog with BSD Zero Clause License | 6 votes |
function PostSearch({ posts }) {
return (
<Autocomplete
disableClearable
options={posts}
onInputChange={(event, value, reason) => {
if (reason === 'reset' && value) {
const item = posts.find((item) => item.title === value);
if (!item) return;
navigate(item.slug);
}
}}
filterOptions={(options, { inputValue }) =>
options.filter(
({ title, categories }) => title.includes(inputValue) || categories.includes(inputValue),
)
}
getOptionLabel={(option) => option.title}
renderInput={(params) => (
<div className="search-input-wrapper">
<TextField
{...params}
className="search-input"
variant="standard"
size="medium"
InputProps={{
...params.InputProps,
endAdornment: <SearchIcon className="search-icon" />,
}}
/>
</div>
)}
noOptionsText="해당하는 글이 없습니다."
/>
);
}
Example #15
Source File: LanguageSwitcher.js From warsinhk with MIT License | 6 votes |
function LanguageSwitcher(props, context) {
const location = useLocation();
const changeLanguage = lng => {
let fullPath = location.pathname;
if (lng === "en" && !fullPath.includes("/en")) {
fullPath = removePathTrailingSlash(fullPath.replace("/", "/en/"))
navigate(fullPath, { replace: true })
} else if (lng === "zh" && fullPath.includes("/en")) {
fullPath = removePathTrailingSlash(fullPath.replace("/en", "")) || "/"
navigate(fullPath, { replace: true })
}
}
const { t } = useTranslation()
return (
<>
<LocaleButton onClick={() => changeLanguage("zh")}>
{t("text.chinese")}
</LocaleButton>
<ListItemText> | </ListItemText>
<LocaleButton onClick={() => changeLanguage("en")}>
{t("text.english")}
</LocaleButton>
</>
)
}
Example #16
Source File: ProjectListItem.js From Webiu with MIT License | 6 votes |
ProjectListItem = ({title, description, image, slug}) => {
return (
<Col md={4}>
<div className="project-list-item-component" onClick={() => navigate(slug)}>
<img className= "image" alt="project" src={image} />
<div>
<p className= "item-title"> {title}</p>
<p className= "item-descriptiom">
{description.slice(0, 220).trim()}
{description.length > 220 ? "..." : ""}
</p>
</div>
</div>
</Col>
)
}
Example #17
Source File: 404.js From ruhulamin.dev with BSD Zero Clause License | 5 votes |
NotFound = () => {
useEffect(() => navigate("/"), []);
return null;
}
Example #18
Source File: api.js From website with BSD Zero Clause License | 5 votes |
// Sesión
firebase.auth().onAuthStateChanged(function (user) {
if (!user) {
navigate('/login');
}
});
Example #19
Source File: index.js From theouterrim with MIT License | 5 votes |
export default function Index() {
const classes = useStyles()
const [searchQuery, setSearchQuery] = useState("")
return (
<ThemeProvider>
<Dashboard>
<SEO title="Home" />
<Grid item xs={12}>
<Typography className={classes.title} variant="h1" color="primary">
The Outer Rim
</Typography>
<Typography
variant="subtitle1"
className={classes.center}
gutterBottom
>
Fantasy Flight Games' Star Wars role-playing game stats from The
Outer Rim.
</Typography>
<div className={clsx(classes.center, classes.search)}>
<form
onSubmit={event => {
event.preventDefault()
navigate(`/search/?q=${searchQuery}`)
}}
noValidate
autoComplete="off"
>
<TextField
className={classes.textField}
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
}}
inputProps={{
"aria-label": "main search",
autoCapitalize: "off",
autoCorrect: "off",
autoComplete: "off",
}}
variant="outlined"
placeholder="Search..."
name="q"
/>
</form>
</div>
</Grid>
</Dashboard>
</ThemeProvider>
)
}
Example #20
Source File: Bag.test.js From ecommerce with MIT License | 5 votes |
test('should navigate to checkout when bag has products and checkout button is pressed', () => {
const { getByText } = render(filledBagTree);
fireEvent.click(getByText('Checkout'));
expect(navigate).toHaveBeenCalledTimes(1);
expect(navigate).toHaveBeenCalledWith('/checkout');
});
Example #21
Source File: App.js From haskell.foundation with MIT License | 5 votes |
App = ({ element }) => {
function languageOnUpdate ({ lang, prevLang, url, prevURL }) {
if (prevURL && url !== prevURL) navigate(url)
if (prevLang && lang !== prevLang) analytics.autoCapture({ category: analytics.constants.LANGUAGE, action: 'language_updated', label: lang })
}
function themeOnUpdate ({ theme, prevTheme }) {
if (prevTheme && theme !== prevTheme) analytics.autoCapture({ category: analytics.constants.THEME, action: 'theme_updated', label: theme })
}
function getRoutes (lang) {
const routes = config.routes.map(({ path, component, props }) => {
const Component = require(`./routes/${component}.js`).default
const routes = [ <Component {...props} path={path} key={path} /> ]
if (config.localization.createLocalizedPages && config.localization.createDefaultPages) {
routes.push(<Component {...props} key={`/${lang}${path}`} path={`/${lang}${path}`} />)
}
return routes
})
return routes.reduce((accumulator, currentValue) => [ ...accumulator, ...currentValue ], [])
}
return (
<Location>
{({ location: { pathname, search, hash } }) => (
<Language.Provider
location={{ pathname, search, hash }}
availableLanguages={config.availableLanguages}
alternativeLanguages={config.alternativeLanguages}
onUpdate={languageOnUpdate}
useURL={config.localization.useURL}
useNavigator={config.localization.useNavigator}
persistLang={config.localization.persistLang}
>
<Theme.Provider
themes={getThemes()}
onUpdate={themeOnUpdate}
transformTheme={({ config }) => theme.convertThemeToMaterial(config)}
>
<Theme.Consumer>
{({ theme, originalTheme }) => (
<MaterialUIThemeProvider theme={theme}>
<StyledThemeProvider theme={theme}>
<Language.Consumer>
{({ key: lang }) => (
<LinkProvider lang={lang} component={Link}>
<Styles theme={originalTheme.config} />
<GlobalStyles />
<Router>
{getRoutes(lang)}
<DefaultRoute default element={element} />
</Router>
</LinkProvider>
)}
</Language.Consumer>
</StyledThemeProvider>
</MaterialUIThemeProvider>
)}
</Theme.Consumer>
</Theme.Provider>
</Language.Provider>
)}
</Location>
)
}
Example #22
Source File: ComponentsContainer.js From mds-docs with MIT License | 5 votes |
ComponentsContainer = ({
children,
pageTitle,
relativePagePath,
tabs,
pageDescription,
}) => {
const page = relativePagePath.split('/');
const pageName = page[page.length - 1].split('.')[0];
const getTabSlug = (tabIndex) => {
const tabName = tabs[tabIndex];
let tabSlug = '';
if (tabName.length) {
tabSlug = tabName.toLowerCase().replace(/\s/g, '-');
}
return tabSlug;
};
const activeTab =
tabs && tabs.length
? tabs.findIndex(
(tab, index) =>
getTabSlug(index) === pageName.toLowerCase()
)
: '';
const [activeIndex, setActiveIndex] = React.useState(
activeTab || 0
);
const onTabChangeHandler = (tabIndex) => {
const nextTabSlug = getTabSlug(tabIndex);
const pagePath = relativePagePath.split('/');
const pages = pagePath.slice(0, pagePath.length - 1);
const path = `${pages.join('/')}/${nextTabSlug}/`;
navigate(path);
setActiveIndex(tabIndex);
};
return (
<>
<Heading>{pageTitle}</Heading>
<p>{pageDescription}</p>
{tabs && tabs.length && (
<Tabs
activeIndex={activeIndex}
onTabChange={onTabChangeHandler}
className='mb-6 mt-4'
>
{tabs.map((tab) => (
<Tab label={tab}></Tab>
))}
</Tabs>
)}
{children}
</>
);
}
Example #23
Source File: index.js From jamstack-ecommerce with MIT License | 5 votes |
export default function Home({data}) {
const [checkoutSession, setCheckoutSession] = useState();
useEffect(()=>{
(async () =>{
const session = await client.checkout.create();
console.log("session = ",session);
setCheckoutSession(session);
localStorage.setItem("checkoutid",session.id);
})()
},[]);
console.log(data.allShopifyProduct.edges);
return (
<div>
<div>Hello world!</div>
<div style={{margin: "20px"}}>
<div>
Total Price: {checkoutSession && checkoutSession.totalPrice}
</div>
<div>
Total Item: {checkoutSession && checkoutSession.lineItems.length}
</div>
<button onClick={()=>{
navigate("/cart");
}}>Cart</button>
</div>
<div>
{
data.allShopifyProduct.edges.map(({node})=>(
<div key={node.id}>
<div>
Name: {node.title}
</div>
<div>
Description: {node.description}
</div>
<div>
<img width="100px" src={node.images[0].originalSrc} />
</div>
<div>
Price: {node.variants[0].price}
</div>
<div>
<button onClick={async()=>{
const session = await client.checkout.addLineItems(checkoutSession.id,[
{
variantId: node.variants[0].id.split("__")[2],
quantity: 2
}
]);
setCheckoutSession(session);
console.log("Test = ",session);
}}>Add to Cart</button>
</div>
</div>
))
}
</div>
</div>
)
}
Example #24
Source File: gatsby-browser.js From TalkTrack with MIT License | 5 votes |
onRedirectCallback = appState => navigate(appState?.returnTo || '/')
Example #25
Source File: CartStatus.js From jamstack-ecommerce with MIT License | 5 votes |
export default function CartStatus() {
const { totalPrice, cartCount, clearCart } = useShoppingCart();
return (
<div style={{display:"flex", flexDirection:"row", justifyContent:"center", alignItems:"center"}}>
<div className="statusMargin">Total Price: {totalPrice}</div>
<div className="statusMargin">Count: {cartCount}</div>
<button className="statusMargin" onClick={()=>{
navigate("/cart")
}}>
Go To Cart
</button>
<button className="statusMargin" onClick={()=> {
clearCart();
}}>
Clear Cart
</button>
</div>
)
}
Example #26
Source File: privateroute.js From create-magic-app with MIT License | 5 votes |
PrivateRoute = ({ component: Component, location, ...rest }) => {
if (!isLoggedIn() && location.pathname !== `/app/login`) {
navigate(`/app/login`)
return null
}
return <Component {...rest} />
}
Example #27
Source File: search.js From gatsby-digital-garden with MIT License | 5 votes |
export function Search() {
const [query, setQuery] = useState("");
const results = useSearch(query);
const handleChange = useCallback((e) => setQuery(e.target.value), [setQuery]);
return (
<Downshift
onChange={(selection) => navigate(selection.path)}
itemToString={(item) => (item ? item.title : "")}
>
{({
getInputProps,
getItemProps,
getMenuProps,
isOpen,
highlightedIndex,
getRootProps,
}) => (
<div
className="searchWrapper"
{...getRootProps({}, { suppressRefError: true })}
>
<SearchBar
query={query}
onChange={handleChange}
getInputProps={getInputProps}
/>
<Results
isOpen={isOpen}
getMenuProps={getMenuProps}
getItemProps={getItemProps}
results={results}
highlightedIndex={highlightedIndex}
/>
</div>
)}
</Downshift>
);
}
Example #28
Source File: index-page.js From rest.js with MIT License | 5 votes |
onVersionChange(event) {
// when the version select changes, navigate to the slug
// set by its <option> value attribute
navigate(`/` + event.target.value);
}
Example #29
Source File: index.js From medusa with MIT License | 5 votes |
Sidebar = ({ data, api }) => {
const [scrollPos, setScrollPos] = useState(0)
const [colorMode,] = useColorMode()
useEffect(() => {
const nav = document.querySelector("#nav")
const handleScroll = e => {
const pos = e.srcElement.scrollTop / 50
if (pos < 1) {
setScrollPos(pos)
}
}
nav.addEventListener("scroll", handleScroll)
return () => nav.removeEventListener("scroll", handleScroll)
}, [])
return (
<SideBarContainer
sx={{
position: "sticky",
top: "0",
bottom: "0",
height: "100vh",
backgroundColor: "var(--theme-ui-colors-background)",
boxShadow: "sidebarShadow",
minWidth: "var(--side-bar-width)",
flexDirection: "column",
}}
className="sidebar-container"
>
<Flex
sx={{
px: "4",
pt: "3",
background: "var(--theme-ui-colors-background)",
width: "calc(var(--side-bar-width) - 1px)",
flexDirection: "column",
}}
>
<Flex>
<Image
src={colorMode === 'light' ? Logo : LogoDark}
alt="Medusa logo"
onClick={() => navigate("/")}
sx={{
height: "32px",
cursor: "pointer",
}}
/>
</Flex>
<Flex py={4}>
<SideBarSelector api={api} />
</Flex>
</Flex>
<Flex
id="nav"
sx={{
flex: 1,
position: "relative",
px: "3",
pb: "3",
mr: "1px",
flexDirection: "column",
overflowY: "scroll",
pr: "6px",
scrollbarColor: "faded light",
}}
>
<SideBarFade opacity={scrollPos} />
{data.sections.map((s, i) => {
return <SideBarItem item={s} key={i} />
})}
</Flex>
</SideBarContainer>
)
}