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: 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 #2
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 #3
Source File: client.js From gatsby-apollo-wpgraphql-jwt-starter with MIT License | 6 votes |
onErrorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path, extensions }) => {
if (extensions && extensions.code === "invalid-jwt") {
logout(() => navigate("/dashboard/"))
}
console.log(`[GraphQL error]:`, {Message: message, Location: locations, Path: path, Extension: extensions})
})
}
if (networkError) {
console.log(`[Network error]: ${networkError}`)
}
})
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: 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 #6
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 #7
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 #8
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 #9
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 #10
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 #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: 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 #13
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 #14
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 #15
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 #16
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 #17
Source File: 404.js From ResumeOnTheWeb-Gatsby with MIT License | 5 votes |
NotFoundPage = () => {
useEffect(() => {
navigate("/");
}, []);
return null;
}
Example #18
Source File: LoginForm.js From gatsby-apollo-wpgraphql-jwt-starter with MIT License | 5 votes |
LoginForm = () => {
const auth = useAuth();
useEffect(() => {
if (auth.isLoggedIn()) {
navigate(`/dashboard/`, {replace: true})
}
}, [auth])
const [loginUser, { data: loginData }] = useMutation(LOGIN_USER)
const [fields, handleFieldChange] = useFormFields({
username: "",
password: "",
})
const handleSubmit = (e) => {
e.preventDefault()
loginUser({
variables: {
input: {
clientMutationId: uuid(),
username: fields.username,
password: fields.password,
},
},
}).then((response) => {
// console.log("Response", response)
const { login } = response.data
if(login) {
setAuthToken(login.authToken)
setRefreshToken(login.refreshToken, () => navigate("/dashboard/"))
}
})
}
return (
<form method="post" style={{ display: "flex", flexDirection: "column", alignItems: "flex-start" }}
onSubmit={handleSubmit}>
<div style={{display: "flex", flexDirection: "column"}}>
<label htmlFor="username" style={labelStyle}><b>Email</b></label>
<input onChange={handleFieldChange} value={fields.username} style={{ marginRight: 16 }} type="text"
placeholder="Enter username" name="username" required/>
<label htmlFor="password" style={labelStyle}><b>Password</b></label>
<input onChange={handleFieldChange} value={fields.password} type="password" placeholder="Enter Password"
name="password" required/>
</div>
<button style={{ margin: "16px 0" }} type="submit">Login</button>
</form>
)
}
Example #19
Source File: navbar.js From upvision.github.io with MIT License | 5 votes |
function Navbar(props) {
const { mark, setMark, path } = props
let location = path.pathname
const [value, setValue] = React.useState(0)
const [expectedValue, setExpectedValue] = React.useState(0)
const handleChange = (event, newValue) => {
setValue(newValue)
}
React.useEffect(() => {
const index = siteMap.findIndex(site => site === location)
setValue(index * 20)
setExpectedValue(index * 20)
}, [mark, location])
React.useEffect(() => {
let currentValue = value
let timer = setInterval(function () {
if (value === expectedValue) clearInterval(timer)
else {
if (currentValue < expectedValue) setValue(currentValue++)
else if (currentValue > expectedValue) setValue(currentValue--)
}
}, 7)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const handleCommittedChange = (event, newValue) => {
const index = Math.floor(newValue / 20)
const finalValue =
index * 20 + Math.round((newValue - index * 20) / 20) * 20
if (setMark) setMark(finalValue)
let currentValue = value
let timer = setInterval(function () {
if (value === finalValue) clearInterval(timer)
else {
if (currentValue < finalValue) setValue(currentValue++)
else if (currentValue > finalValue) setValue(currentValue--)
}
}, 7)
navigate(siteMap[Math.max(0, finalValue / 20)])
}
// React.useEffect(() => {
// window.addEventListener("scroll", event => {
// console.log(event)
// })
// })
return (
<>
<Grid container spacing={3} justify="center" id="nav">
<Grid item xs={10} md={8} lg={6}>
<ThemeProvider theme={muiTheme}>
<Slider
min={0}
max={100}
value={value}
onChange={handleChange}
onChangeCommitted={handleCommittedChange}
aria-labelledby="continuous-slider"
marks={marks}
/>
</ThemeProvider>
</Grid>
</Grid>
</>
)
}
Example #20
Source File: BannerModule.js From barcadia with MIT License | 5 votes |
BannerModule = ({ children, title, subTitle, price, enquire }) => {
function scrollToArea() {
navigate("#topContent")
}
return (
<>
<BannerModuleStyles>
{children ? (
children
) : (
<StaticImage
className="banner__image"
imgClassName="banner__image--content"
src="../../../static/macbook-color.jpg"
alt="Banner Image"
layout="fullWidth"
placeholder="blurred"
/>
)}
<div className="container">
<div className="banner__content">
{title && (
<h1>
{title}
<span style={{ color: "var(--primary)" }}>.</span>
</h1>
)}
{subTitle && <h2>{subTitle}</h2>}
{price && (
<h2 className="price">
£{price}
<span style={{ color: "var(--primary)" }}>.</span>
</h2>
)}
<div className="banner__btns">
{enquire && (
<Button
className="btn"
text="Enquire Now"
as={Link}
to="/contact"
/>
)}
<Button onClick={scrollToArea} text="Learn More" />
</div>
</div>
</div>
<div className="gradient"></div>
</BannerModuleStyles>
<span id="topContent"></span>
</>
)
}
Example #21
Source File: layout.js From crypto-dappy-learning-hub with Apache License 2.0 | 5 votes |
Layout = ({ children }) => (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
menuLinks {
name
link
}
}
}
}
`}
render={data => (
<Wrapper>
<CookieConsent
location="bottom"
buttonText="Accept"
declineButtonText="Decline"
cookieName="gatsby-gdpr-google-analytics"
>
This site uses cookies to enhance the user experience.
</CookieConsent>
<Header />
<Bottom>
<Navbar menuLinks={data.site.siteMetadata.menuLinks} />
<Content>
{children}
</Content>
</Bottom>
<Footer>
<FooterContent>Made with ❤️ and ☕ by the <a href="https://forum.onflow.org/c/community-projects/cryptodappy/35">Flow community</a></FooterContent>
<AffiliateLogo
onClick={() => navigate('https://onflow.org/')}
src={`${config.ASSETS_URL}/images/PoweredByFlow_Horizontal.png`} />
</Footer>
</Wrapper>
)}
/>
)
Example #22
Source File: landing.js From carbon-badges with Apache License 2.0 | 5 votes |
Landing = () => {
const { login, token } = useAuth();
useEffect(() => {
if (token) {
navigate("/badges", {
replace: true,
});
}
}, [token]);
return (
<Layout homepage>
<Helmet title="Carbon Badges" />
<div className="bx--grid bx--grid--full-width">
<div className="bx--row">
<div className="bx--col-lg-8 bx--col-md-7">
<h1 className={style.heading}>
The Carbon Design System offers IBM Digital Badges based on
completion of the{" "}
<a href="https://www.carbondesignsystem.com/tutorial/angular/overview">
Carbon Angular
</a>
,{" "}
<a href="https://www.carbondesignsystem.com/tutorial/react/overview">
Carbon React
</a>
,{" "}
<a href="https://www.carbondesignsystem.com/tutorial/vue/overview">
Carbon Vue
</a>
, and{" "}
<a href="https://www.ibm.com/standards/carbon/developing/web-components-tutorial/overview">
Carbon for IBM.com Web Components
</a>{" "}
tutorials. Log in with GitHub to view and apply for Carbon badges.
</h1>
</div>
</div>
<div className="bx--row">
<div className="bx--col-lg-3">
<Button
className={style.button}
kind="primary"
onClick={() => login()}
renderIcon={ArrowRight32}
type="button"
>
Log in with GitHub
</Button>
</div>
</div>
<div className="bx--row">
<div className="bx--col">
<p className={style.copy}>
Don't have a GitHub account?{" "}
<a href="https://github.com/join">Join GitHub</a>
</p>
</div>
</div>
<div className="bx--row">
<div className="bx--offset-lg-10 bx--col-lg-2 bx--offset-md-6 bx--col-md-2 bx--offset-sm-3 bx--col-sm-1">
<img
className={style.pictogram}
src={pictogram}
alt="Carbon pictogram"
/>
</div>
</div>
</div>
</Layout>
);
}
Example #23
Source File: SearchField.js From testnets-cardano-org with MIT License | 5 votes |
SearchField = ({ onSearch }) => {
const onFormSubmit = (search, lang, setSearch) => (e) => {
e.preventDefault()
analytics.capture({ category: 'form', action: 'submit_search', label: search })
onSearch && onSearch(search)
setSearch('')
navigate(`/${lang}/search/?query=${encodeURIComponent(search)}&page=1`)
}
return (
<GlobalContentQuery
render={globalContent => (
<Language.Consumer>
{({ key: lang }) => (
<Search.Consumer>
{({ search, setSearch }) => (
<Form
onSubmit={onFormSubmit(search, lang, setSearch)}
aria-label={globalContent.search_form_aria_label}
>
<Input
type='text'
name='search-field'
placeholder={globalContent.search}
value={search}
onChange={(e) => setSearch(e.target.value)}
aria-label={globalContent.search_form_aria_label}
/>
<Submit
type='submit'
onClick={(e) => analytics.click({ category: 'form', label: 'search_submit', event: e })}
aria-label={globalContent.search_form_submit_aria_label}
>
<FiSearch />
</Submit>
</Form>
)}
</Search.Consumer>
)}
</Language.Consumer>
)}
/>
)
}
Example #24
Source File: Auth0Provider.js From climatescape.org with MIT License | 5 votes |
DefaultRedirectCallback = ({ returnTo }) => {
navigate(returnTo || "/")
}
Example #25
Source File: 404.js From ruhulamin.dev with BSD Zero Clause License | 5 votes |
NotFound = () => {
useEffect(() => navigate("/"), []);
return null;
}
Example #26
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 #27
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 #28
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 #29
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}
</>
);
}