react-router-dom#useLocation TypeScript 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: AppContext.tsx    From one-platform with MIT License 6 votes vote down vote up
export default function AppContextProvider ( props: any ) {
  const { appId } = useParams<RouteParams>();
  const router = useHistory();
  const location = useLocation();

  const { app, loading, setApp: setOriginalApp } = useAppAPI(appId);

  const setApp = (newAppId: string) => {
    const newPath = location.pathname.replace( appId, newAppId ) + location.search + location.hash;
    router.push( newPath );
  }

  const forceRefreshApp = ( newApp: App ) => {
    setOriginalApp( { ...app, ...newApp} );
  }

  return (
    <AppContext.Provider value={ { appId, app, loading, setApp, forceRefreshApp }}>
      {props.children}
    </AppContext.Provider>
  )
}
Example #2
Source File: OrderQuery.ts    From Demae with MIT License 6 votes vote down vote up
useSalesMethod = (): SalesMethod | undefined => {

	const { search } = useLocation()
	const params = new URLSearchParams(search);
	const salesMethod = params.get("salesMethod") || ""

	if (["instore", "online", "pickup", "download"].includes(salesMethod)) {
		return salesMethod as SalesMethod
	} else {
		return undefined
	}
}
Example #3
Source File: ScrollToTop.tsx    From akashlytics with GNU General Public License v3.0 6 votes vote down vote up
ScrollToTop: React.FunctionComponent = () => {
  const { pathname } = useLocation();

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

  return null;
}
Example #4
Source File: index.ts    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
export function useGoogleAnalytics(
  trackingId: string,
  debug: boolean = process.env.NODE_ENV !== 'production',
) {
  const location = useLocation();
  const trackingIdRef = useRef<string>(trackingId);
  const debugRef = useRef<boolean>(debug);

  useEffect(() => {
    if (!debugRef.current) {
      const script1 = document.createElement('script');
      script1.src = `https://www.googletagmanager.com/gtag/js?id=${trackingIdRef.current}`;
      script1.async = true;

      document.body.appendChild(script1);

      const script2 = document.createElement('script');
      script2.text = gtag(trackingIdRef.current);

      document.body.appendChild(script2);
    } else {
      console.log('GTAG INIT:', trackingIdRef.current);
    }
  }, []);

  useEffect(() => {
    if (!debugRef.current && window.gtag) {
      window.gtag('config', trackingIdRef.current, {
        page_location: location.pathname + location.search,
        page_path: location.pathname,
      });
    } else if (debugRef.current) {
      console.log('GTAG PUSH: ', location.pathname + location.search);
    }
  }, [location]);
}
Example #5
Source File: Navigation.tsx    From bluebubbles-server with Apache License 2.0 6 votes vote down vote up
NavItem = ({ icon, to, children, ...rest }: NavItemProps) => {
    const location = useLocation();
    return (
        <Flex
            align="center"
            p="4"
            mx="4"
            borderRadius="lg"
            role="group"
            cursor="pointer"
            _hover={{
                bg: 'brand.primary',
                color: 'white'
            }}
            color={location.pathname === to ? 'brand.primary' : 'current'}
            {...rest}
        >
            {icon && (
                <Icon
                    mr="4"
                    fontSize="16"
                    _groupHover={{
                        color: 'white'
                    }}
                    as={icon}
                />
            )}
            {children}
        </Flex>
    );
}
Example #6
Source File: App.tsx    From clarity with Apache License 2.0 6 votes vote down vote up
// the hook to send pageView to GA.
function usePageViews() {
  let location = useLocation();

  useEffect(() => {
    if (ENABLE_GA) {
      ReactGA.pageview(location.pathname);
    }
  }, [location]);
}
Example #7
Source File: Menu.tsx    From eth2stats-dashboard with MIT License 6 votes vote down vote up
Menu: React.FC<IMenuProps> = (props) => {
    let {url} = useRouteMatch();
    let {pathname} = useLocation();

    return (
        <ul className="flex items-center">
            <li className="mr-2 sm:mr-6 h-6 border-r border-grey-600 hidden sm:block"
                role="separator"/>
            <li className="mr-4 flex items-center">
                <Link to={`${url}`}>
                    <div className={`mr-4 flex items-center justify-center border p-2 w-10
                                    ${pathname === `${url}`
                        ? "border-blue-500 bg-blue-500 text-white"
                        : "text-grey-600 border-grey-600 hover:border-white hover:text-white transition"}`}>
                        <FontAwesomeIcon icon="list"/>
                    </div>
                </Link>
                <Link to={`${url}/map`}>
                    <div className={`flex items-center justify-center border p-2 w-10
                                    ${pathname === `${url}/map`
                        ? "border-blue-500 bg-blue-500 text-white"
                        : "text-grey-600 border-grey-600 hover:border-white hover:text-white transition"} `}>
                        <FontAwesomeIcon icon="map"/>
                    </div>
                </Link>
            </li>
        </ul>
    );
}
Example #8
Source File: useQuery.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
function useQuery() {
  const { search } = useLocation();
  const history = useHistory();

  const query = useMemo(() => new URLSearchParams(search), [search]);

  const setQueryParam = (key: string, value: string) => {
    const query = new URLSearchParams(window.location.search);
    query.delete(key);
    query.append(key, value);
    history.replace({ search: query.toString() });
  };

  return { query, setQueryParam };
}
Example #9
Source File: TutorPanel.tsx    From TutorBase with MIT License 6 votes vote down vote up
Panel = (props: IProps) => {
    let dispatch = useDispatch();
    let sidebarToggled = useSelector(selectSidebarToggled);

    let params : string = useLocation().pathname;
    let extension:string = params.split('/')[2];

    return (
        <div id="panel-wrapper">
            <Navbar className={classNames("navbar-expand-lg", "navbar-light", "bg-light", "border-bottom", "shadow")}>
                <Button className="btn-red" id="menu-toggle" onClick={() => {
                    dispatch(actions.toggleSidebar());
                }}>☰</Button>
            </Navbar>
            {/* <div class="container-fluid">
                <h2 className={classNames("mt-4", "hr")}>Tutor Dashboard</h2>
            </div>

            <div class="container-fluid">
                <h5 className={classNames("mt-4", "hr")}>Courses</h5>
                <p>This is where the tutor will be able to add or drop classes they are tutoring for.</p>
                <Button variant="danger">Add New Course</Button>
                <Button variant="danger">Drop Course</Button>

            </div> */}
            {extension === "overview" ? <TutorOverview></TutorOverview> : null}
            {extension === "meetings" ? <Meetings mode="Tutor"></Meetings> : null}
            {extension === "history" ? <TutorHistory></TutorHistory> : null}
            {extension === "analytics" ? <DataVisualization /> : null}
            {extension === "settings" ? <Settings></Settings> : null}

        </div>
    );
}
Example #10
Source File: App.tsx    From dnd-character-sheets with MIT License 6 votes vote down vote up
function ScrollToTop() {
  const { pathname } = useLocation();

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

  return null;
}
Example #11
Source File: ScrollToTop.tsx    From react-tutorials with MIT License 6 votes vote down vote up
export default function ScrollToTop() {
  const { pathname, search } = useLocation()

  useEffect(
    () => () => {
      try {
        window.scroll({
          top: 0,
          left: 0,
          behavior: 'smooth',
        })
      } catch (error) {
        // older browsers fallback
        window.scrollTo(0, 0)
      }
    },
    [pathname, search]
  )
  return null
}
Example #12
Source File: VersionSwitch.tsx    From cuiswap with GNU General Public License v3.0 6 votes vote down vote up
export default function VersionSwitch() {
  const version = useToggledVersion()
  const location = useLocation()
  const query = useParsedQueryString()
  const versionSwitchAvailable = location.pathname === '/swap' || location.pathname === '/send'

  const toggleDest = useMemo(() => {
    return versionSwitchAvailable
      ? {
          ...location,
          search: `?${stringify({ ...query, use: version === Version.v1 ? undefined : Version.v1 })}`
        }
      : location
  }, [location, query, version, versionSwitchAvailable])

  const handleClick = useCallback(
    e => {
      if (!versionSwitchAvailable) e.preventDefault()
    },
    [versionSwitchAvailable]
  )

  const toggle = (
    <VersionToggle enabled={versionSwitchAvailable} to={toggleDest} onClick={handleClick}>
      <VersionLabel enabled={version === Version.v2 || !versionSwitchAvailable}>V2</VersionLabel>
      <VersionLabel enabled={version === Version.v1 && versionSwitchAvailable}>V1</VersionLabel>
    </VersionToggle>
  )
  return versionSwitchAvailable ? (
    toggle
  ) : (
    <MouseoverTooltip text="This page is only compatible with Uniswap V2.">{toggle}</MouseoverTooltip>
  )
}
Example #13
Source File: room.tsx    From vorb.chat with GNU Affero General Public License v3.0 6 votes vote down vote up
Instruction: React.SFC = () => {
  const routerLocation = useLocation();

  const url = useMemo(() => {
    return window.location.toString();
  }, [routerLocation]);

  const shareLink = useCallback((e) => {
    e.preventDefault();
    navigator.clipboard.writeText(url);
  }, [url]);

  return <div className="room_instruction">
      <h2>The room is empty.</h2>
      Share the <a href={url} onClick={shareLink}>link</a> to invite others
      <br/>
      You can reconfigure what ressources you want to share once you granted permission
      <br/>
      Mute yourself by clicking the speaker button
      <br/>
      Share your screen
      <br/>
      For feedback contact us at <a href="mailto:[email protected]">[email protected]</a>
  </div>
}
Example #14
Source File: Routes.tsx    From taskcafe with MIT License 6 votes vote down vote up
UserRequiredRoute: React.FC<any> = ({ children }) => {
  const { user } = useCurrentUser();
  const location = useLocation();
  if (user) {
    return children;
  }
  return (
    <Redirect
      to={{
        pathname: '/login',
        state: { redirect: location.pathname },
      }}
    />
  );
}
Example #15
Source File: MainLayout.tsx    From atlas with GNU General Public License v3.0 6 votes vote down vote up
MainLayout: React.FC = () => {
  const scrollPosition = useRef<number>(0)
  const location = useLocation()
  const navigationType = useNavigationType()
  const [cachedLocation, setCachedLocation] = useState(location)
  const locationState = location.state as RoutingState
  const [openDialog, closeDialog] = useConfirmationModal({
    title: 'Outdated browser detected',
    description:
      'It seems the browser version you are using is not fully supported by Joystream. Some of the features may be broken or not accessible. For the best experience, please upgrade your browser to the latest version.',
    iconType: 'warning',
    primaryButton: {
      text: 'Click here to see instructions',
      onClick: () => window.open('https://www.whatismybrowser.com/guides/how-to-update-your-browser/auto'),
    },
    onExitClick: () => closeDialog(),
  })

  useEffect(() => {
    if (isBrowserOutdated) {
      openDialog()
    }
  }, [openDialog])

  useEffect(() => {
    if (location.pathname === cachedLocation.pathname) {
      return
    }

    setCachedLocation(location)

    if (locationState?.overlaidLocation?.pathname === location.pathname) {
      // if exiting routing overlay, skip scroll to top
      return
    }
    if (navigationType !== 'POP') {
      scrollPosition.current = window.scrollY
    }
    // delay scroll to allow transition to finish first
    setTimeout(() => {
      window.scrollTo(0, navigationType !== 'POP' ? 0 : scrollPosition.current)
    }, parseInt(transitions.timings.routing) + ROUTING_ANIMATION_OFFSET)
  }, [location, cachedLocation, locationState, navigationType])

  return (
    <>
      <CookiePopover />
      <Routes>
        <Route path={absoluteRoutes.embedded.video()} element={<EmbeddedView />} />
        <Route path={BASE_PATHS.viewer + '/*'} element={<ViewerLayout />} />
        <Route path={BASE_PATHS.legal + '/*'} element={<LegalLayout />} />
        <Route path={BASE_PATHS.studio + '/*'} element={<LoadableStudioLayout />} />
        <Route path={BASE_PATHS.playground + '/*'} element={<LoadablePlaygroundLayout />} />
      </Routes>
      <AdminOverlay />
    </>
  )
}
Example #16
Source File: MainHeader.tsx    From Shopping-Cart with MIT License 6 votes vote down vote up
MainHeader = () => {
  const { Title, Text } = Typography;
  const location = useLocation();

  const isCartedPage: boolean = location.pathname === CART_PATH;

  return (
    <>
      <Row>
        <Col xs={20} sm={12}>
          <NavLink to={PRODUCTS_LIST_PATH}>
            <Title style={titleStyle}>KYU SHOP</Title>
          </NavLink>
        </Col>
        <Col xs={4} sm={12} style={{ textAlign: 'right' }}>
          {isCartedPage ? (
            <NavLinkIconButton
              to={PRODUCTS_LIST_PATH}
              icon="appstore"
              text="상품목록"
            />
          ) : (
            <NavLinkIconButton
              to={CART_PATH}
              icon="shopping-cart"
              text="장바구니"
            />
          )}
        </Col>
      </Row>
    </>
  );
}
Example #17
Source File: MenuItemsList.tsx    From dashboard-layout with MIT License 6 votes vote down vote up
MenuItemsList = () => {
  const classes = useStyles();

  const { pathname } = useLocation();

  return (
    <Grid>
      <List className={classes.padding}>
        {DRAWER_LIST.map(({ literal, route, Icon }) => (
          <MenuItem
            Icon={Icon}
            literal={literal}
            route={route}
            key={route}
            selected={pathname === route}
          />
        ))}
      </List>
    </Grid>
  );
}
Example #18
Source File: routes.ts    From gonear-name with The Unlicense 6 votes vote down vote up
useRouteCheck = (): CheckState => {
  const [check, setCheck] = useState<CheckState>(checkState)
  const location = useLocation()
  
  useEffect(() => {
    const {pathname} = location
    const state: CheckState = {
      isMarket: market.includes(pathname) || pathname.indexOf('/bid') >= 0,
      isOffer: pathname.indexOf('/offer') >= 0,
      isRules: pathname === '/rules',
      isProfile: pathname === '/profile'
    }
    setCheck(state)
  }, [location])
  return check
}
Example #19
Source File: useParsedQueryString.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
export default function useParsedQueryString(): ParsedQs {
  const { search } = useLocation();
  return useMemo(
    () =>
      search && search.length > 1
        ? parse(search, { parseArrays: false, ignoreQueryPrefix: true })
        : {},
    [search],
  );
}
Example #20
Source File: FuseTabBar.tsx    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
TabLink = ({
  route,
  text,
  ...others
}: {
  route: string;
  text: string;
  [key: string]: any;
}) => {
  const isMobile = useIsSmallScreen();

  const location = useLocation();

  return (
    <Link
      /* @ts-ignore */
      as={RouterLink}
      className="no-underline"
      to={route}
      ml={isMobile ? 0 : 4}
      mt={isMobile ? 4 : 0}
      {...others}
    >
      <DashboardBox
        height="35px"
        {...(route ===
        location.pathname.replace(/\/+$/, "") + window.location.search
          ? activeStyle
          : noop)}
      >
        <Center expand px={2} fontWeight="bold">
          {text}
        </Center>
      </DashboardBox>
    </Link>
  );
}
Example #21
Source File: utils.ts    From abrechnung with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useQuery() {
    return new URLSearchParams(useLocation().search);
}
Example #22
Source File: Header.tsx    From Intro_to_React with GNU General Public License v2.0 6 votes vote down vote up
MyLink: FC<{ title: string; to: string }> = ({ title, to }) => {
  const { pathname } = useLocation()
  const currentStyle = pathname === to ? style.selected : style.noSelected

  return (
    <Link to={to} className={style.myLink + " " + currentStyle}>
      <div className={style.title}>{title}</div>
    </Link>
  )
}
Example #23
Source File: DesktopSideBar.tsx    From Tachidesk-WebUI with Mozilla Public License 2.0 6 votes vote down vote up
export default function DesktopSideBar({ navBarItems }: IProps) {
    const location = useLocation();
    const theme = useTheme();

    const iconFor = (path: string, IconComponent: any, SelectedIconComponent: any) => {
        if (location.pathname === path) return <SelectedIconComponent sx={{ color: 'primary.main' }} fontSize="large" />;
        return <IconComponent sx={{ color: (theme.palette.mode === 'dark') ? 'grey.A400' : 'grey.600' }} fontSize="large" />;
    };

    return (
        <SideNavBarContainer>
            {
                // eslint-disable-next-line react/destructuring-assignment
                navBarItems.map(({
                    path, title, IconComponent, SelectedIconComponent,
                }: NavbarItem) => (
                    <Link to={path} style={{ color: 'inherit', textDecoration: 'none' }} key={path}>
                        <ListItem disableRipple button key={title}>
                            <ListItemIcon sx={{ minWidth: '0' }}>
                                <Tooltip placement="right" title={title}>
                                    {iconFor(path, IconComponent, SelectedIconComponent)}
                                </Tooltip>
                            </ListItemIcon>
                        </ListItem>
                    </Link>
                ))
            }
        </SideNavBarContainer>
    );
}
Example #24
Source File: LocationInfo.tsx    From react-starter-boilerplate with MIT License 6 votes vote down vote up
LocationInfo = () => {
  const location = useLocation();

  return (
    <div>
      <p>
        Current location (provided by{' '}
        <a href="https://reacttraining.com/react-router/web/api/Hooks/uselocation">
          <code>useLocation</code>
        </a>{' '}
        hook from <a href="https://github.com/ReactTraining/react-router">react-router</a>):
      </p>
      <CodeBlock>{JSON.stringify(location)}</CodeBlock>
    </div>
  );
}
Example #25
Source File: OverviewColumn.tsx    From sybil-interface with GNU General Public License v3.0 6 votes vote down vote up
export default function OverviewColumn() {
  const [activeProtocol] = useActiveProtocol()
  const location = useLocation()

  return (
    <Wrapper backgroundColor={activeProtocol?.secondaryColor}>
      <AutoColumn gap="md">
        <TYPE.main
          fontSize="24px"
          fontWeight="700"
          color={activeProtocol?.primaryColor}
          style={{ marginBottom: '1rem' }}
        >
          {activeProtocol?.name}
        </TYPE.main>
        <TabOption
          as={Link}
          to={'/delegates/' + activeProtocol?.id}
          selected={location.pathname.includes('delegates')}
          color={activeProtocol?.primaryColor}
          color2={activeProtocol?.secondaryColor}
        >
          Discover Delegates
        </TabOption>
        <TabOption
          as={Link}
          to={'/proposals/' + activeProtocol?.id}
          selected={location.pathname.includes('proposals')}
          color={activeProtocol?.primaryColor}
          color2={activeProtocol?.secondaryColor}
        >
          View Proposals
        </TabOption>
      </AutoColumn>
    </Wrapper>
  )
}
Example #26
Source File: menu.tsx    From kinopub.webos with MIT License 6 votes vote down vote up
Menu: React.FC<Props> = ({ className, ...props }) => {
  const location = useLocation();

  return (
    <nav className={cx('h-screen w-52 flex flex-col justify-between overflow-y-auto', className)} {...props}>
      {map(menuItems, (list, idx) => (
        <ul key={idx}>
          {map(list, (item: MenuItem) => (
            <li key={item.href}>
              <Link href={item.href} icon={item.icon} active={location.pathname.startsWith(item.href)}>
                {item.name}
              </Link>
            </li>
          ))}
        </ul>
      ))}
    </nav>
  );
}
Example #27
Source File: PrivateRoute.tsx    From frontend with Apache License 2.0 6 votes vote down vote up
PrivateRoute: React.FunctionComponent<PropType> = ({
  component: Component,
}) => {
  const { loggedIn } = useUserState();
  const location = useLocation();

  if (loggedIn) {
    return <Component />;
  }

  return <Navigate to={routes.LOGIN} state={{ from: location.pathname }} />;
}
Example #28
Source File: NotFoundPage.tsx    From devex with GNU General Public License v3.0 6 votes vote down vote up
NotFoundPage: React.FC = () => {

  const location = useLocation()

  return <>
    <Card className='error-card'>
      <Card.Body>
        <h4 className='mb-3'>
          Sorry! Could not find requested page. Try again later!
        </h4>
        <h6 className='mb-2'>
          Network: <strong>{useNetworkUrl()}</strong>
        </h6>
        <h6>
          Search: <strong>{useSearchParams()}</strong>
        </h6>
        <Link to={{ pathname: '/', search: location.search }}>
          <Button id='error-btn' className='mt-4'>
            <span>
              Return to Dashboard
              </span>
          </Button>
        </Link>
      </Card.Body>
    </Card>
  </>
}
Example #29
Source File: DemoPage.tsx    From ChatUI with MIT License 6 votes vote down vote up
DemoPage = ({ children }: DemoPageProps) => {
  const { pathname } = useLocation();
  const name = pathname.slice(1);

  return (
    <div className="demo-page" data-page={name}>
      <div className="demo-header">
        <Link className="demo-header-back" to="/" aria-label="Back">
          <svg viewBox="0 0 1000 1000">
            <path d="M296.114 508.035c-3.22-13.597.473-28.499 11.079-39.105l333.912-333.912c16.271-16.272 42.653-16.272 58.925 0s16.272 42.654 0 58.926L395.504 498.47l304.574 304.574c16.272 16.272 16.272 42.654 0 58.926s-42.654 16.272-58.926 0L307.241 528.058a41.472 41.472 0 0 1-11.127-20.023z" />
          </svg>
        </Link>
        <h1 className="demo-header-title">{toPascalCase(name)}</h1>
      </div>
      {children}
    </div>
  );
}