react-router-dom#useLocation JavaScript Examples

The following examples show how to use react-router-dom#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: index.js    From ocp-advisor-frontend with Apache License 2.0 7 votes vote down vote up
Breadcrumbs = ({ current }) => {
  const intl = useIntl();
  const location = useLocation();
  const splitUrl = location.pathname.split('/');

  return (
    <div>
      <Breadcrumb ouiaId="detail">
        <BreadcrumbItem className="breadcrumb-item">
          <Link to={`/${splitUrl[1]}`}>
            {`${intl.formatMessage(messages.insightsHeader)} ${splitUrl[1]}`}
          </Link>
        </BreadcrumbItem>
        <BreadcrumbItem className="breadcrumb-item" isActive>
          {current}
        </BreadcrumbItem>
      </Breadcrumb>
    </div>
  );
}
Example #2
Source File: Authentication.js    From sed-frontend with Apache License 2.0 7 votes vote down vote up
Authentication = ({ children }) => {
  const queryClient = useQueryClient();
  const location = useLocation();

  const { isLoading, isFetching, isSuccess, isError } = useUser();

  useEffect(() => {
    isSuccess && window.insights?.chrome?.hideGlobalFilter();
  }, [isSuccess]);

  useEffect(() => {
    /**
     * On every rerender, based on URL change (location.pathname),
     * reset the user's status to loading before authenticating again.
     */
    queryClient.invalidateQueries('user');
  }, [location.pathname]);

  if (isError === true) {
    return <Unavailable />;
  } else if (isLoading === true || isFetching === true) {
    return <Loading />;
  } else if (isSuccess === true) {
    return <>{children}</>;
  }
}
Example #3
Source File: Navigation.js    From foster-together-fe with MIT License 6 votes vote down vote up
export default function Navigation() {
  const [open, setOpen] = useState(false)
  const { pathname } = useLocation()
  const { push } = useHistory()

  return (
    <NavBar>
      <Logo>
        <LogoImg src={require('../../../images/logo.png')} />
      </Logo>
      <Nav>
        {routes.map((route, i) => (
          <Tab
            key={i}
            onClick={() => push(route.path)}
            active={pathname === route.path}
          >
            <img src={route.icon} alt={route.alt} />
            <p>{route.title}</p>
          </Tab>
        ))}
      </Nav>
      <UtilitiesContainer open={open} setOpen={setOpen} />
    </NavBar>
  )
}
Example #4
Source File: variableMainContent.jsx    From neighborhood-chef-fe with MIT License 6 votes vote down vote up
function VariableMainContent(props) {
  const location = useLocation();
  const [urlLocation, setUrlLocation] = useState(
    location.pathname.split("/")[1]
  );
  useEffect(() => {
    setUrlLocation(location.pathname.split("/")[1]);
  }, [location]);

  switch (urlLocation) {
    case !urlLocation:
      return <p>homepage</p>;
    case "grid":
      return <Dashboard />;
    case "dashboard":
      return <Dashboard />;
    case "create-event":
      return <CreateEvent />;
    case "view-events":
      return <ViewEvents />;
    case "events":
      return <FullEvent {...props} />;
    default:
      return <p>you did a bad</p>;
  }
}
Example #5
Source File: App.js    From social-media-strategy-fe with MIT License 6 votes vote down vote up
function App(props) {
  initializeAnalytics();
  const { authService } = useOktaAuth();
  const dispatch = useDispatch();
  const history = useHistory();
  const location = useLocation();
  const user = useSelector((state) => state.user);

  useEffect(() => {
    if (location.pathname === "/connect/twitter/callback") return;
    if (!user.initialized) {
      dispatch(initializeUser(authService, history));
      return;
    }
    // eslint-disable-next-line
  }, [user, location]);

  return (
    <Switch>
      <Route exact path="/login" component={LoginOkta} />
      <Route path="/implicit/callback" component={LoginCallback} />
      <Route>
        <NavMenuTemplate>
          <SecureRoute path="/home" component={Home} />
          <SecureRoute path="/analytics" component={Analytics} />
          <SecureRoute path="/connect" component={ConnectAccounts} />
        </NavMenuTemplate>
      </Route>
    </Switch>
  );
}
Example #6
Source File: SplashNav.jsx    From trashpanda-fe with MIT License 6 votes vote down vote up
SplashNav = () => {
  const [selectedPage, setSelectedPage] = useState(0);
  const { pathname } = useLocation();

  useEffect(() => {
    switch (pathname) {
      case "/splash":
        setSelectedPage(0);
        break;
      case "/splash/team":
        setSelectedPage(1);
        break;
    }
  }, [pathname]);

  return (
    <Container>
      <FlexContainer>
        <Title>Trash Panda</Title>
        <NavLink selected={selectedPage == 0}>
          <Link to="/splash">What We Do</Link>
        </NavLink>
        <NavLink selected={selectedPage == 1}>
          <Link to="/splash/team">Meet the Team</Link>
        </NavLink>
      </FlexContainer>
      <a href="https://play.google.com/store/apps/details?id=com.thetrashpanda.twa">
        <PlayBadge src={playBadgeImg} />
      </a>
    </Container>
  );
}
Example #7
Source File: ScrollToTop.jsx    From Corona-tracker with MIT License 6 votes vote down vote up
export default function ScrollToTop() {
  const { pathname } = useLocation();
  const contentEl = document.getElementById('content');

  useEffect(() => {
    if (contentEl) contentEl.scrollTop = 0;
  }, [pathname, contentEl]);

  return null;
}
Example #8
Source File: AnalyticsPageViewLogger.js    From app with MIT License 6 votes vote down vote up
export default function AnalyticsPageViewLogger() {
  const location = useLocation();
  const analytics = useAnalytics();
  const user = useUser();
  // By passing `user.uid` to the second argument of `useEffect`,
  // we only set user id when it exists
  useEffect(() => {
    if (user?.uid) {
      analytics.setUserId(user.uid);
    }
  }, [user?.uid]); // eslint-disable-line react-hooks/exhaustive-deps

  // By passing `location.pathname` to the second argument of `useEffect`,
  // we only log on first render and when the `pathname` changes
  useEffect(() => {
    analytics.logEvent('page-view', { path_name: location.pathname });
  }, [location.pathname]); // eslint-disable-line react-hooks/exhaustive-deps

  return null;
}
Example #9
Source File: Signin.js    From ponce-tournois-mario-kart with MIT License 6 votes vote down vote up
function Signin() {
    const dispatch = useDispatch();
    const history = useHistory();
    const { search } = useLocation();

    const onSignin = () => history.push('/');

    useEffect(() => {
        const { token } = queryString.parse(search);
        dispatch(signin(token, onSignin));
    }, []);

    return <></>;
}
Example #10
Source File: index.jsx    From react-firebase-admin with MIT License 6 votes vote down vote up
NotFound = () => {
  const location = useLocation();

  const { isAuth } = useSelector(
    state => ({
      isAuth: !!state.auth.userData.id
    }),
    shallowEqual
  );

  const userPath = isAuth ? path.ROOT : path.LOGIN;

  return (
    <section className="hero is-fullheight">
      <div className="hero-body">
        <section className={`section ${classes.section}`}>
          <div className="container">
            <div className="columns is-vcentered is-desktop">
              <div className="column has-text-centered">
                <h1 className="title">{useFormatMessage('NotFound.404')}</h1>
                <p className="subtitle">
                  {useFormatMessage('NotFound.url', { url: location.pathname })}
                </p>
                <Link className="button is-info is-normal" to={userPath}>
                  {useFormatMessage('NotFound.back')}
                </Link>
              </div>
              <div className="column has-text-centered">
                <img src={NotFoudImage} alt="404 error" />
              </div>
            </div>
          </div>
        </section>
      </div>
    </section>
  );
}
Example #11
Source File: ToastContainer.js    From airdnd-frontend with MIT License 6 votes vote down vote up
ToastContainer = ({ state, onClickUndo }) => {
  // ! redux
  const { data } = useSelector(state => state.message.messages);
  const { toast } = useSelector(state => state.message.toastState);

  // ! query
  const query = useLocation();
  const { filter } = qs.parse(query.search, {
    ignoreQueryPrefix: true,
  });

  const hasMsgs = data && data[`${filter || 'all'}`].length;

  return (
    <Toast
      state={state}
      toast={toast}
      onClickUndo={onClickUndo}
      hasMsgs={hasMsgs}
    />
  );
}
Example #12
Source File: index.js    From HackShack-Session-Landing-Page with MIT License 6 votes vote down vote up
ScrollToTop = () => {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}
Example #13
Source File: ScrollToTop.js    From Website with MIT License 6 votes vote down vote up
export default function ScrollToTop() {
	const { pathname } = useLocation();

	useEffect(() => {
		window.scrollTo(0, 0);
	}, [pathname]);

	return null;
}
Example #14
Source File: rooter.js    From Queen with MIT License 6 votes vote down vote up
Rooter = () => {
  const { standalone } = useContext(AppContext);
  const { pathname } = useLocation();

  return (
    <Switch>
      <Route
        path={`/queen/:${READ_ONLY}?/questionnaire/:idQ/survey-unit/:idSU`}
        component={secure(OrchestratorManager)}
      />
      <Route path={`/queen/:${READ_ONLY}?/survey-unit/:idSU`} component={secure(QueenRedirect)} />
      {!standalone && <Route path="/queen/synchronize" component={secure(Synchronize)} />}
      <Route path="/queen/visualize" component={Visualizer} />
      {!standalone &&
        !pathname.startsWith('/queen/authentication') &&
        pathname.startsWith('/queen') && <Redirect to="/queen/visualize" />}
      {standalone && !pathname.startsWith('/queen/authentication') && (
        <Redirect to="/queen/visualize" />
      )}
    </Switch>
  );
}
Example #15
Source File: Headerbar.js    From spotify-clone-client with MIT License 6 votes vote down vote up
export default function Headerbar({children}) {
    const location = useLocation()

    return (
        <div className="header-bar" style={{background: location.pathname === '/'? null:'none'}}>
            {children}
        </div>
    )
}
Example #16
Source File: Header.jsx    From stonks-frontend with MIT License 6 votes vote down vote up
export default function Header() {
  const location = useLocation();
  const [links, setLinks] = useState([
    {
      _id: Math.random().toString(),
      title: "DashBoard",
      link: "/",
    },
    {
      _id: Math.random().toString(),
      title: "About",
      link: "/about",
    },
    {
      _id: Math.random().toString(),
      title: "Contact",
      link: "/contact",
    },
  ]);
  return (
    <div className="header">
      <Link to="/">
        <div className="logo">
          <img src={Logo} alt="err" />
          <p>STONKS</p>
        </div>
      </Link>
      <div className="header-options">
        {links?.map(({ _id, title, link }) => (
          <Link to={link}>
            <p className={`${location.pathname === link && "active"}`}>
              {title}
            </p>
          </Link>
        ))}
      </div>
    </div>
  );
}
Example #17
Source File: NavSection.js    From course-manager with MIT License 6 votes vote down vote up
export default function NavSection({ navConfig, ...other }) {
  const { pathname } = useLocation();
  const match = (path) => (path ? !!matchPath({ path, end: false }, pathname) : false);

  return (
    <Box {...other}>
      <List disablePadding>
        {navConfig.map((item) => (
          <NavItem key={item.title} item={item} active={match} />
        ))}
      </List>
    </Box>
  );
}
Example #18
Source File: ConfigLoader.js    From dshop with MIT License 6 votes vote down vote up
ConfigLoader = ({ children }) => {
  const location = useLocation()
  const { config, setActiveShop } = useConfig()

  useEffect(() => {
    if (!config) {
      setActiveShop(true)
    }
  }, [config])

  useEffect(() => {
    if (location.state && location.state.scrollToTop) {
      window.scrollTo(0, 0)
    }
  }, [location.pathname])

  if (!config) {
    return 'Loading'
  }

  return children
}
Example #19
Source File: AppFooter.js    From react-todo-app with MIT License 6 votes vote down vote up
function AppFooter() {
  const location = useLocation();

  return (
    <footer className="pb-6 mt-6 text-center">
      { location.pathname === "/" ? (
        <NavLink
          to="/about"
          className="transition duration-500 ease-in-out text-gray-800 border-b border-gray-800 hover:text-gray-500 hover:border-gray-500"
          data-testid="footer-about-link"
        >
          About
        </NavLink>
      ) : (
        <p>Made by <a className="transition duration-500 ease-in-out font-medium text-pink-600 hover:text-pink-500" href="https://phixyn.com/" target="_blank">Phixyn</a></p>
      )}

    </footer>
  )
}
Example #20
Source File: ErrorReducerCatcher.js    From access-requests-frontend with Apache License 2.0 6 votes vote down vote up
ErroReducerCatcher = ({ children }) => {
  const errorCode = useSelector(({ errorReducer: { errorCode } }) => errorCode);
  const { pathname } = useLocation();
  const dispatch = useDispatch();

  useEffect(() => {
    if (errorCode) {
      dispatch({ type: API_ERROR, payload: undefined });
    }
  }, [pathname]);

  if (errorCode) {
    const State = errorStates[errorCode];
    const name = 'Access Requests';
    return <State serviceName={name} />;
  }

  return children;
}
Example #21
Source File: App.js    From malware-detection-frontend with Apache License 2.0 6 votes vote down vote up
App = (props) => {
    const { pathname } = useLocation();
    const { push } = useHistory();
    const appNavClick = useMemo(
        () => ({
            signatures(redirect) {
                insights.chrome.appNavClick({ id: 'signatures', redirect });
            },
            systems(redirect) {
                insights.chrome.appNavClick({ id: 'systems', redirect });
            }
        }),
        []
    );

    useEffect(() => {
        insights.chrome.init();
        const baseComponentUrl = pathname.split('/')[4];
        const unregister = insights.chrome.on('APP_NAVIGATION', (event) => {
            if (event.domEvent) {
                push(`/${event.navId}`);
                appNavClick[baseComponentUrl] !== undefined
                    ? appNavClick[baseComponentUrl](true)
                    : appNavClick.signatures;
            }
        });

        return () => unregister();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return  <Routes childProps={props} />;
}
Example #22
Source File: index.js    From sed-frontend with Apache License 2.0 6 votes vote down vote up
NavTabs = ({ tabItems, TabsProps: { className, ...TabsProps } }) => {
  const { push } = useHistory();
  const { pathname, search } = useLocation();
  const activeTab = tabItems.find(({ pathname: tabPathname }) =>
    pathname.includes(tabPathname)
  );
  const handleTabClick = (_event, tabIndex) =>
    push({ pathname: tabItems[tabIndex].pathname, search });

  return (
    <Tabs
      {...TabsProps}
      className={classnames('ins-c-navtabs', className)}
      activeKey={activeTab ? activeTab.eventKey : 0}
      onSelect={handleTabClick}
    >
      {tabItems.map((item) => (
        <Tab key={item.eventKey} {...item} />
      ))}
    </Tabs>
  );
}
Example #23
Source File: Chunk.js    From howurls.work with MIT License 6 votes vote down vote up
Chunk = ({
  children,
  color,
  align,
  orientation,
  explanation,
  url,
}) => {
  const location = useLocation()
  const history = useHistory()

  const isActive = useMemo(() => {
    return location.pathname.includes(url)
  }, [location.pathname, url])

  const handleChunkClick = useCallback(() => {
    history.replace(url)
  }, [url, history])

  const linkClassNames = [isActive && 'active'].filter(Boolean).join(' ')

  return (
    <Container color={color}>
      <button className={linkClassNames} onClick={handleChunkClick}>
        {children}
      </button>
      {isActive && explanation && (
        <Popover orientation={orientation} align={align}>
          {explanation()}
        </Popover>
      )}
    </Container>
  )
}
Example #24
Source File: LoginPage.js    From instaclone with Apache License 2.0 6 votes vote down vote up
LoginPage = ({ currentUser, githubSignInStart }) => {
  const history = useHistory();
  const { search } = useLocation();
  if (currentUser) history.push('/');
  const params = new URLSearchParams(search);
  const code = params.get('code');
  const authState = params.get('state');

  useEffect(() => {
    if (code) {
      if (!authState === sessionStorage.getItem('authState')) {
        return console.warn('Auth state does not match.');
      }
      githubSignInStart(code);
    }
  }, [authState, code, githubSignInStart]);

  return (
    <main data-test="page-login" className="login-page">
      <div className="login-page__showcase"></div>
      <LoginCard />
    </main>
  );
}
Example #25
Source File: NavigationItem.js    From say-their-names-web with MIT License 6 votes vote down vote up
NavigationItem = ({ name, path }) => {
  const location = useLocation();
  let active = '';

  if (path === '/' && path === location.pathname) {
    active = 'active';
  }

  if (path === '/donations' && location.pathname.includes('donate')) {
    active = 'active';
  }

  if (path === '/petitions' && location.pathname.includes('sign')) {
    active = 'active';
  }

  if (path !== '/' && location.pathname.includes(path)) {
    active = 'active';
  }

  return (
    <StyledNavigationLinks>
      <Link to={path} className={active}>
        {name}
      </Link>
    </StyledNavigationLinks>
  );
}
Example #26
Source File: ResultTable.stories.js    From sampo-ui with MIT License 6 votes vote down vote up
basic = () => {
  const facetResults = useSelector(state => state.perspective1)
  const location = useLocation()
  return (
    <div style={{ width: '100%', height: '100%' }}>
      <ResultTable
        data={facetResults}
        facetUpdateID={0}
        resultClass='perspective1'
        facetClass='perspective1'
        fetchPaginatedResults={() => null}
        updatePage={() => null}
        updateRowsPerPage={() => null}
        sortResults={() => null}
        location={location}
        rootUrl=''
      />
    </div>
  )
}
Example #27
Source File: Header.jsx    From sgmr-service with MIT License 6 votes vote down vote up
Header = () => {
  const location = useLocation();

  return (
    <header className="govuk-header" role="banner" data-module="govuk-header">
      <a href="#main-content" className="govuk-skip-link">Skip to main content</a>

      <div className="govuk-header__container govuk-width-container">
        <label hidden htmlFor="link-div">GOV.UK</label>
        <div className="govuk-header__logo" id="link-div">
          <a className="govuk-header__link govuk-header__link--homepage" href="/">
            <span className="govuk-header__logotype">
              <svg role="presentation" focusable="false" className="govuk-header__logotype-crown" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 132 97" height="32" width="36">
                <path fill="currentColor" fillRule="evenodd" d="M25 30.2c3.5 1.5 7.7-.2 9.1-3.7 1.5-3.6-.2-7.8-3.9-9.2-3.6-1.4-7.6.3-9.1 3.9-1.4 3.5.3 7.5 3.9 9zM9 39.5c3.6 1.5 7.8-.2 9.2-3.7 1.5-3.6-.2-7.8-3.9-9.1-3.6-1.5-7.6.2-9.1 3.8-1.4 3.5.3 7.5 3.8 9zM4.4 57.2c3.5 1.5 7.7-.2 9.1-3.8 1.5-3.6-.2-7.7-3.9-9.1-3.5-1.5-7.6.3-9.1 3.8-1.4 3.5.3 7.6 3.9 9.1zm38.3-21.4c3.5 1.5 7.7-.2 9.1-3.8 1.5-3.6-.2-7.7-3.9-9.1-3.6-1.5-7.6.3-9.1 3.8-1.3 3.6.4 7.7 3.9 9.1zm64.4-5.6c-3.6 1.5-7.8-.2-9.1-3.7-1.5-3.6.2-7.8 3.8-9.2 3.6-1.4 7.7.3 9.2 3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 11.6c-4.2-.1-8-1-12.3-5.4l1.4 16.4c3.9-5.5 8.5-7.7 10.9-7.3-.3 5.8-.9 12.8-11.1 13.8-7.2.6-12.9-2.9-13.5-7.2-.7-5 3.8-8.3 7.1-3.1 2.7-8.7-4.6-11.6-9.4-6.2 3.7-8.5 3.6-14.7-4.6-20.8-5.8 7.6-5 13.9 2.2 21.1-4.7-2.6-11.9.1-7.7 8.8 2.3-5.5 7.1-4.2 8.1.5.7 3.3-1.3 7.1-5.7 7.9-3.5.7-9-1.8-13.5-11.2 2.5.1 4.7 1.3 7.5 3.3l-4.7-15.4c-1.2 4.4-2.7 7.2-4.3 8.7-1.1-3-.9-5.3 0-10.2l-9.5 3.4c5 6.9 9.9 16.7 14 33.5 14.8-2.1 30.8-3.2 47.7-3.2z" />
                <image src="/assets/images/govuk-logotype-crown.png" className="govuk-header__logotype-crown-fallback-image" />
              </svg>
              <span className="govuk-header__logotype-text">GOV.UK</span>
            </span>
          </a>
        </div>
        <Nav urlStem={location.pathname} />
      </div>
    </header>
  );
}
Example #28
Source File: GenreCard.js    From Anime-Tracker-Web-App with MIT License 6 votes vote down vote up
GenreCard = () => {
  const location = useLocation();

  const [genreArray, setGenreArray] = useState([]);

  // calling the api only one
  useEffect(() => {
    callGenreApi();
    // eslint-disable-next-line
  }, []);

  const callGenreApi = async () => {
    // awaiting so the async call can be complete
    let genreData = await apiDataGenres(location.state.genreID);
    setGenreArray(genreData);
  };
  return (
    <div>
      <DisplayCommonCard animeData={genreArray} />
    </div>
  );
}
Example #29
Source File: FinancesApp.js    From actual with MIT License 6 votes vote down vote up
// import Debugger from './Debugger';

function URLBar() {
  let location = useLocation();

  return (
    <View
      style={{
        position: 'absolute',
        bottom: 0,
        right: 0,
        margin: 15,
        backgroundColor: colors.n9,
        padding: 8,
        borderRadius: 6
      }}
    >
      {location.pathname}
    </View>
  );
}