react-router-dom#Navigate TypeScript Examples

The following examples show how to use react-router-dom#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: AdminRoutes.tsx    From nodestatus with MIT License 9 votes vote down vote up
AdminRoutes: FC = () => {
  const routes: RouteObject[] = [
    {
      path: '/dashboard',
      element: <Dashboard />
    },
    {
      path: '/management',
      element: <Management />
    },
    {
      path: '/incidents',
      element: <Incidents />
    },
    {
      path: '/',
      element: <Navigate to="/dashboard" />
    }
  ];

  return useRoutes(routes);
}
Example #2
Source File: index-page.tsx    From platyplus with MIT License 6 votes vote down vote up
IndexPage: React.FC<{ title?: string }> = ({
  title = 'Index page'
}) => {
  const signedIn = useAuthenticated()
  const { state, isFetching } = useAppConfig()
  if (signedIn) {
    if (isFetching) return null
    return <Navigate to={state.home || '/home'} />
  } else
    return (
      <HeaderTitleWrapper title={title}>
        <h2>Welcome</h2>
        <Link to="/login">Login</Link>
        <br />
        <Link to="/register">Register</Link>
      </HeaderTitleWrapper>
    )
}
Example #3
Source File: OnboardingNavigator.tsx    From celo-web-wallet with MIT License 6 votes vote down vote up
export function OnboardingNavigator() {
  // If wallet exists in storage don't allow user back into onboarding flow
  if (hasAccounts() || hasAccount_v1()) {
    return <Navigate to="/" replace={true} />
  }

  // Force navigation to fail screen if providers are unable to connect
  const isConnected = useAppSelector((s) => s.wallet.isConnected, shallowEqual)
  if (isConnected === false) throw new Error('Unable to connect to network.')

  // Otherwise, render screen as normal
  return <Outlet />
}
Example #4
Source File: LayoutHandler.tsx    From nodestatus with MIT License 6 votes vote down vote up
LayoutHandler: FC = () => {
  const { data, error } = useSWR<IResp>('/api/session');
  return (
    error
      ? <Navigate to="/login" />
      : !data
        ? <Loading />
        : <Layout />
  );
}
Example #5
Source File: App.tsx    From cli with Apache License 2.0 6 votes vote down vote up
export default function App() {
  return (
    <Router>
      <Routes>
        <Route
          path="/"
          element={
            <Navigate to={isEnvValid() === true ? '/home' : '/error'} replace />
          }
        />
        <Route path="/home" element={<Home />} />
        <Route path="/error" element={<Error />} />
      </Routes>
    </Router>
  );
}
Example #6
Source File: RequireAuth.tsx    From raspiblitz-web with MIT License 6 votes vote down vote up
RequireAuth: FC<Props> = ({ children }) => {
  let { isLoggedIn } = useContext(AppContext);
  let location = useLocation();

  if (!isLoggedIn) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
}
Example #7
Source File: index.tsx    From genshin-optimizer with MIT License 6 votes vote down vote up
export default function CharacterDisplay() {
  const navigate = useNavigate();
  let { characterKey } = useParams<{ characterKey?: CharacterKey }>();
  const invalidKey = !allCharacterKeys.includes(characterKey as any ?? "")
  if (invalidKey)
    return <Navigate to="/characters" />
  return <Box my={1} display="flex" flexDirection="column" gap={1}>
    {characterKey && <Suspense fallback={<Skeleton variant="rectangular" width="100%" height={1000} />}>
      <CharacterDisplayCard characterKey={characterKey} onClose={() => navigate("/characters")} />
    </Suspense>}
  </Box>
}
Example #8
Source File: index.tsx    From mui-toolpad with MIT License 6 votes vote down vote up
function FileEditor({ appId }: FileEditorProps) {
  const dom = useDom();
  const app = appDom.getApp(dom);
  const { pages = [] } = appDom.getChildNodes(dom, app);

  const firstPage = pages.length > 0 ? pages[0] : null;

  return (
    <Routes>
      <Route element={<AppEditorShell appId={appId} />}>
        <Route path="connections/:nodeId" element={<ConnectionEditor appId={appId} />} />
        <Route path="apis/:nodeId" element={<ApiEditor appId={appId} />} />
        <Route path="pages/:nodeId" element={<PageEditor appId={appId} />} />
        <Route path="codeComponents/:nodeId" element={<CodeComponentEditor appId={appId} />} />
        <Route path="codeComponents/:nodeId" element={<CodeComponentEditor appId={appId} />} />
        <Route
          index
          element={
            firstPage ? <Navigate to={`pages/${firstPage.id}`} /> : <NoPageFound appId={appId} />
          }
        />
      </Route>
    </Routes>
  );
}
Example #9
Source File: SchoolCharacters.tsx    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
EnhancedSchoolCharacters: VFC = () => {
  const { schoolCode = '' } = useParams();
  const { search } = useLocation();
  const queryParams = new URLSearchParams(search);
  const isLoading = !!queryParams.get('loading');
  const schoolCodeList = Object.keys(charactersData);

  if (schoolCodeList.includes(schoolCode)) {
    const { school, players } = charactersData[schoolCode];

    return (
      <SchoolCharacters
        school={school}
        characters={players}
        isLoading={isLoading}
      />
    );
  }

  return <Navigate to="/" replace />;
}
Example #10
Source File: EvmApp.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
export function EvmApp() {
  return (
    <EvmAppProviders>
      <div>
        <GlobalStyle />
        <Header />
        <Routes>
          <Route index={true} element={<Dashboard />} />
          <Route path="/mypage" element={<Mypage />} />
          <Route path="/earn" element={<Earn />} />
          <Route path="/borrow" element={<Borrow />} />
          <Route path="/terms" element={<TermsOfService />} />
          <Route path="/gov/" element={<GovernanceMain />} />
          <Route path="/poll/:id" element={<PollDetail />} />
          <Route path="/bridge/restore" element={<Restore />} />
          <Route path="/claim/all" element={<ClaimAll />} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
        <BackgroundTransactions />
      </div>
    </EvmAppProviders>
  );
}
Example #11
Source File: private-route.tsx    From platyplus with MIT License 6 votes vote down vote up
PrivateRoute: React.FC<RouteProps> = ({ children, ...rest }) => {
  const signedIn = useAuthenticated()
  const tableInfoReady = useIsTableInfoReady()
  const location = useLocation()

  // return (
  //   <Route
  //     {...rest}
  //     children={({ location }) => {
  //       // user is logged-in
  if (signedIn === null) {
    return <Loading backdrop content="loading authentication status..." />
  }
  if (signedIn && !tableInfoReady) {
    return <Loading backdrop content="loading tables information..." />
  }
  if (!signedIn) {
    return (
      <Navigate
        replace
        to={{
          pathname: '/login'
        }}
        state={{ from: location }}
      />
    )
  }
  return <div>{children}</div>
  //       return children
  //     }}
  //   />
  // )
}
Example #12
Source File: index.tsx    From rabet-extension with GNU General Public License v3.0 6 votes vote down vote up
ProtectedRoute = ({ children }: { children: JSX.Element }) => {
  const isOnLine = checkOffline();
  const user = useTypedSelector((store) => store.user);

  if (!isOnLine) {
    return <Navigate to={RouteName.OfflineMode} />;
  }

  if (!user.logged) {
    if (user.registered) {
      return <Navigate to={RouteName.Login} />;
    }

    return <Navigate to={RouteName.Introduction} />;
  }

  return children;
}
Example #13
Source File: PrivateRoute.tsx    From react-auth-kit with Apache License 2.0 6 votes vote down vote up
RequireAuth: React.FunctionComponent<RequireAuthProps> =
  ({children, loginPath}) => {
    const context = React.useContext(AuthContext);
    if (context === null) {
      throw new
      Error('Auth Provider is missing. ' +
      'Please add the AuthProvider before Router');
    }

    const isAuth = () => {
      if (context.authState.auth &&
      (new Date(context.authState.auth.expiresAt) > new Date())) {
        return true;
      } else {
        context.dispatch(doSignOut());
        return false;
      }
    };
    const location = useLocation();

    if (!isAuth()) {
    // Redirect them to the /login page, but save the current location they were
    // trying to go to when they were redirected. This allows us to send them
    // along to that page after they login, which is a nicer user experience
    // than dropping them off on the home page.
      return <Navigate to={loginPath} state={{from: location}} replace />;
    }

    return children;
  }
Example #14
Source File: ProtectedRoute.tsx    From pali-wallet with MIT License 6 votes vote down vote up
export function ProtectedRoute({ element }: { element: JSX.Element }) {
  const { isUnlocked } = getController().wallet;

  if (!isUnlocked()) {
    return <Navigate to={{ pathname: '/' }} />;
  }

  return element;
}
Example #15
Source File: NotFoundScreen.tsx    From celo-web-wallet with MIT License 6 votes vote down vote up
export function NotFoundScreen() {
  if (config.isElectron) {
    // On Electron, just route 404's back home
    // Necessary because initial route is not <filepath>/index.html
    return <Navigate to="/" replace={true} />
  }

  return (
    <OnboardingScreenFrame>
      <Fade show={true} duration="2s">
        <Box direction="column" align="center">
          <h1 css={style.h1}>This page could not be found, sorry!</h1>
          <img width="160em" src={NotFoundIcon} alt="Not Found" css={style.img} />
          <h3 css={style.h3}>
            Please check the URL or go{' '}
            <Link to="/" css={style.linkHome}>
              back to home
            </Link>
            .
          </h3>
        </Box>
      </Fade>
    </OnboardingScreenFrame>
  )
}
Example #16
Source File: routes.tsx    From netflix-clone with MIT License 6 votes vote down vote up
export function ProtectedRoute({ user, children }: any) {
    if (user) return children;
    else
        return (
            <Navigate
                state={{ from: location }}
                to={{
                    pathname: "signin"
                }}
            />
        );
}
Example #17
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 #18
Source File: StudioEntrypoint.tsx    From atlas with GNU General Public License v3.0 6 votes vote down vote up
StudioEntrypoint: React.FC<StudioEntrypointProps> = ({ enterLocation }) => {
  const {
    activeAccountId,
    activeMemberId,
    activeChannelId,
    extensionConnected,
    memberships,
    membershipsLoading,
    activeMembership,
    activeMembershipLoading,
  } = useUser()

  const hasMemberships = !membershipsLoading && memberships?.length

  const accountSet = !!activeAccountId && extensionConnected === true
  const memberSet = accountSet && !!activeMemberId
  const channelSet = memberSet && !!activeChannelId

  // not signed user with not account set and/or no extension
  if (!accountSet) {
    return <Navigate to={absoluteRoutes.studio.signIn()} replace />
  }

  // signed users
  if (!activeMembershipLoading && !membershipsLoading && !channelSet && hasMemberships && memberSet) {
    if (!activeMembership?.channels.length) {
      return <Navigate to={absoluteRoutes.studio.signIn()} replace />
    }
    return <Navigate to={enterLocation} replace />
  }

  if (channelSet) {
    return <Navigate to={DEFAULT_ROUTE} replace />
  }

  return <StudioLoading />
}
Example #19
Source File: root-router.tsx    From shippo with MIT License 6 votes vote down vote up
Component: React.FC<RootRouteProps> = ({ result }) => {
  const history = useNavigate()
  const location = useLocation()

  useMount(() => {
    console.log(result)
    const resource = result[0].data.resource
    localStorage.setItem('__PASSPORT', resource.passport)
    if (resource.uid > 0) {
      message.success(`已经登录,UID为${resource.uid}`)
      if (location.pathname.startsWith('/passport')) {
        history('/')
      }
    } else {
      message.error('没有登录')
      history('/passport')
    }
  })

  return (
    <Routes>
      <Route path="/passport" element={<Passport />}>
        <Route path="" element={<Page_passport />}></Route>
      </Route>
      <Route path="/dashboard" element={<Home />}>
        <Route path="" element={withLoading(lazy(() => import('~/pages/dashboard')))}></Route>
      </Route>
      <Route path="/read" element={<ReadLayout />}></Route>
      <Route path="/creation" element={<CreationLayout />}></Route>
      <Route path="*" element={<Navigate to="/dashboard" replace />}></Route>
    </Routes>
  )
}
Example #20
Source File: ScreenUser.tsx    From sync-party with GNU General Public License v3.0 5 votes vote down vote up
export default function ScreenUser(): JSX.Element | null {
    const [loggedOut, setLoggedOut] = useState(false);
    const [redirect, setRedirect] = useState(false);

    const dispatch = useDispatch();
    const { t } = useTranslation();
    const user = useSelector((state: RootAppState) => state.globalState.user);

    const handleLogoutButton = async (): Promise<void> => {
        try {
            const response = await Axios.post('/api/logout', {}, axiosConfig());

            if (response.data.success === true) {
                setLoggedOut(true);

                dispatch(setGlobalState(baseState));
            } else {
                dispatch(
                    setGlobalState({
                        errorMessage: t(
                            `apiResponseMessages.${response.data.msg}`
                        )
                    })
                );
            }
        } catch (error) {
            dispatch(
                setGlobalState({
                    errorMessage: t(`errors.logoutError`)
                })
            );
        }
    };

    if (loggedOut || redirect) {
        return <Navigate to="/"></Navigate>;
    }

    return user ? (
        <div className="container">
            <div className="flex flex-row justify-between">
                <Heading
                    text={`${t('common.user')}: ${user.username}`}
                    size={2}
                    className="mb-5"
                ></Heading>
                <ButtonIcon
                    onClick={(): void => setRedirect(true)}
                    icon={
                        <FontAwesomeIcon
                            icon={faTimes}
                            size="lg"
                        ></FontAwesomeIcon>
                    }
                    className="p-1"
                    color="text-gray-200"
                    title={t('common.close')}
                ></ButtonIcon>
            </div>

            <ButtonLink
                onClick={handleLogoutButton}
                text={t('common.logout')}
                className="text-red-600 hover:text-red-500"
                padding="pr-1"
            ></ButtonLink>
        </div>
    ) : null;
}
Example #21
Source File: rewards.anc-governance.tsx    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
function RewardsAncUstLpBase({ className }: RewardsAncUstLpProps) {
  const navigate = useNavigate();

  const pageMatch = useMatch(`/${ancGovernancePathname}/:view`);

  const subTab = useMemo<Item | undefined>(() => {
    switch (pageMatch?.params.view) {
      case 'stake':
        return stakeItems[0];
      case 'unstake':
        return stakeItems[1];
    }
  }, [pageMatch?.params.view]);

  const subTabChange = useCallback(
    (nextTab: Item) => {
      navigate({
        pathname: `/${ancGovernancePathname}/${nextTab.value}`,
      });
    },
    [navigate],
  );

  return (
    <CenteredLayout className={className}>
      <header>
        <h1>
          <Circles radius={24} backgroundColors={['#2C2C2C']}>
            <GifIcon
              src={anc80gif}
              style={{ fontSize: '2em', borderRadius: '50%' }}
            />
          </Circles>
          ANC Governance
        </h1>
      </header>

      <Section>
        <RulerTab
          className="subtab"
          items={stakeItems}
          selectedItem={subTab ?? stakeItems[0]}
          onChange={subTabChange}
          labelFunction={({ label }) => label}
          keyFunction={({ value }) => value}
          tooltipFunction={({ tooltip }) => tooltip}
        />

        <div className="form">
          <Routes>
            <Route path="/stake" element={<AncGovernanceStake />} />
            <Route path="unstake" element={<AncGovernanceUnstake />} />
            <Route
              index={true}
              element={<Navigate to={`/${ancGovernancePathname}/stake`} />}
            />
            <Route
              path="*"
              element={<Navigate to={`/${ancGovernancePathname}/stake`} />}
            />
          </Routes>
          <Outlet />
        </div>
      </Section>
    </CenteredLayout>
  );
}
Example #22
Source File: root-router.tsx    From shippo with MIT License 5 votes vote down vote up
Component: React.FC<RootRouteProps> = ({ result }) => {
  const history = useNavigate()
  const location = useLocation()

  useMount(() => {
    console.log(result)
    const resource = result[0].data.resource
    localStorage.setItem('__PASSPORT', resource.passport)
    if (resource.uid > 0) {
      message.success(`已经登录,UID为${resource.uid}`)
      if (location.pathname.startsWith('/passport')) {
        history('/')
      }
    } else {
      message.error('没有登录')
      history('/passport')
    }
  })

  return (
    <Routes>
      <Route path="/passport" element={<Passport />}>
        <Route path="" element={<Page_passport />}></Route>
      </Route>
      <Route path="/transform" element={<Transform />}></Route>
      <Route path="/dashboard" element={<Home />}>
        <Route path="" element={withLoading(lazy(() => import('~/pages/dashboard')))}></Route>
      </Route>
      <Route path="/users" element={<Home />}>
        <Route path="" element={withLoading(lazy(() => import('~/pages/users')))}></Route>
      </Route>
      <Route path="/temp/*" element={<Home />}>
        <Route
          path="temp_trade_20220108"
          element={withLoading(lazy(() => import('~/pages/temp/temp_trade_20220108')))}
        ></Route>
      </Route>
      <Route path="/permission/*" element={<Home />}>
        <Route
          path="role"
          element={withLoading(lazy(() => import('~/pages/permission/role')))}
        ></Route>
        <Route
          path="access"
          element={withLoading(lazy(() => import('~/pages/permission/access')))}
        ></Route>
        <Route
          path="policy"
          element={withLoading(lazy(() => import('~/pages/permission/policy')))}
        ></Route>
      </Route>
      <Route path="*" element={<Navigate to="/dashboard" replace />}></Route>
    </Routes>
  )
}
Example #23
Source File: App.tsx    From ExpressLRS-Configurator with GNU General Public License v3.0 5 votes vote down vote up
export default function App() {
  const {
    networkDevices,
    newNetworkDevices,
    removeDeviceFromNewList,
  } = useNetworkDevices();

  const [device, setDevice] = useState<string | null>('');

  const onDeviceChange = useCallback(
    (dnsDevice: MulticastDnsInformation | null) => {
      const dnsDeviceName = dnsDevice?.name ?? null;
      setDevice(dnsDeviceName);
      if (dnsDevice) {
        const dnsDeviceType = dnsDevice.type.toUpperCase();
        if (dnsDeviceType === 'TX' || dnsDeviceType === 'RX') {
          window.location.href = '#/configurator';
        } else if (dnsDeviceType === 'TXBP' || dnsDeviceType === 'VRX') {
          window.location.href = '#/backpack';
        }
      }
    },
    []
  );

  return (
    <StyledEngineProvider injectFirst>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <ApolloProvider client={client}>
          <AppStateProvider>
            <HashRouter>
              <Routes>
                <Route
                  path="/"
                  element={<Navigate replace to="/configurator" />}
                />
                <Route
                  path="/configurator"
                  element={
                    <ConfiguratorView
                      key="configurator"
                      gitRepository={Config.expressLRSGit}
                      selectedDevice={device}
                      networkDevices={networkDevices}
                      onDeviceChange={onDeviceChange}
                      deviceType={DeviceType.ExpressLRS}
                    />
                  }
                />
                <Route
                  path="/backpack"
                  element={
                    <ConfiguratorView
                      key="backpack"
                      gitRepository={Config.backpackGit}
                      selectedDevice={device}
                      networkDevices={networkDevices}
                      onDeviceChange={onDeviceChange}
                      deviceType={DeviceType.Backpack}
                    />
                  }
                />
                <Route path="/settings" element={<SettingsView />} />
                <Route path="/logs" element={<LogsView />} />
                <Route path="/serial-monitor" element={<SerialMonitorView />} />
                <Route path="/support" element={<SupportView />} />
              </Routes>
            </HashRouter>
            <WifiDeviceNotification
              newNetworkDevices={newNetworkDevices}
              removeDeviceFromNewList={removeDeviceFromNewList}
              onDeviceChange={onDeviceChange}
            />
          </AppStateProvider>
        </ApolloProvider>
      </ThemeProvider>
    </StyledEngineProvider>
  );
}
Example #24
Source File: App.tsx    From minesweeper with MIT License 5 votes vote down vote up
Routing: FC = () => (
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/minesweeper">
      <Route
        path="hooks"
        element={
          <Suspense fallback={<div>Loading minesweeper with hooks...</div>}>
            <MinesweeperWithHooks />
          </Suspense>
        }
      >
        <Route
          path=":username"
          element={
            <Suspense fallback={<div>Loading minesweeper with hooks...</div>}>
              <MinesweeperWithHooks />
            </Suspense>
          }
        />
      </Route>
      <Route
        path="usereducer"
        element={
          <Suspense
            fallback={<div>Loading minesweeper with useReducer...</div>}
          >
            <MinesweeperWithUseReducer />
          </Suspense>
        }
      />
      <Route
        path="reactredux"
        element={
          <Suspense
            fallback={<div>Loading minesweeper with ReactRedux...</div>}
          >
            <MinesweeperWithReactRedux />
          </Suspense>
        }
      />
    </Route>
    <Route path="*" element={<Navigate to="/" />} />
  </Routes>
)
Example #25
Source File: Routes.tsx    From mysterium-vpn-desktop with MIT License 5 votes vote down vote up
Routes: React.FC = observer(function Routes() {
    const { connection, config } = useStores()
    const location = useLocation()
    const nakedTitleBar = [locations.onboarding, locations.terms, locations.registering, locations.loading].find((p) =>
        location.pathname.startsWith(p),
    )
    return (
        <WinContents>
            <Main>
                {nakedTitleBar ? <NakedTitleBar /> : <TitleBar />}
                <ReactRoutes>
                    <Route path="/loading" element={<StartupLoadingView />} />
                    <Route path="/onboarding/*">
                        <Route path="welcome" element={<Welcome />} />
                        <Route path="intro/*">
                            <Route path="*" element={<Step1 />} />
                            <Route path="2" element={<Step2 />} />
                            <Route path="3" element={<Step3 />} />
                            <Route path="4" element={<Step4 />} />
                        </Route>
                        <Route path="identity/setup" element={<IdentitySetup />} />
                        <Route path="identity/backup" element={<IdentityBackup />} />
                        <Route path="topup-prompt" element={<InitialTopup />} />
                        <Route path="wallet/topup/*" element={<TopupRoutes />} />
                        <Route path="*" element={<Navigate replace to="welcome" />} />
                    </Route>
                    <Route path="/terms" element={<AcceptTermsView />} />
                    <Route path="/registration" element={<IdentityRegistrationView />} />
                    <Route
                        path="/consumer"
                        element={
                            <Navigate
                                to={
                                    connection.status === ConnectionStatus.NOT_CONNECTED
                                        ? locations.proposals
                                        : locations.connection
                                }
                            />
                        }
                    />
                    <Route path="/consumer/proposals/*">
                        <Route path="quick-connect" element={<QuickConnectView />} />
                        <Route path="manual-connect" element={<ManualConnectView />} />
                        <Route
                            path="*"
                            element={<Navigate replace to={config.quickConnect ? "quick-connect" : "manual-connect"} />}
                        />
                    </Route>
                    <Route path="/consumer/connection" element={<ConnectedView />} />
                    <Route path="/settings/*" element={<SettingsView />}>
                        <Route path="filters" element={<SettingsFilters />} />
                        <Route path="connection" element={<SettingsConnection />} />
                        <Route path="mysterium-id" element={<SettingsMysteriumId />} />
                        <Route path="*" element={<Navigate replace to="filters" />} />
                    </Route>
                    <Route path="/wallet" element={<WalletView />} />
                    <Route path="/wallet/topup/*" element={<TopupRoutes />} />
                    <Route path="/help/*" element={<HelpView />}>
                        <Route path="bug-report" element={<HelpContentReportIssue />} />
                        <Route path="terms-and-conditions" element={<HelpContentTermsAndConditions />} />
                        <Route path="*" element={<Navigate to="bug-report" />} />
                    </Route>
                    <Route path="*" element={<Navigate replace to="/loading" />} />
                </ReactRoutes>
            </Main>
        </WinContents>
    )
})
Example #26
Source File: ToolpadApp.tsx    From mui-toolpad with MIT License 5 votes vote down vote up
export default function ToolpadApp({ basename, appId, version, dom }: ToolpadAppProps) {
  const root = appDom.getApp(dom);
  const { pages = [], themes = [] } = appDom.getChildNodes(dom, root);

  const theme = themes.length > 0 ? themes[0] : null;

  const appContext = React.useMemo(() => ({ appId, version }), [appId, version]);

  const queryClient = React.useMemo(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            retry: false,
          },
        },
      }),
    [],
  );

  const [resetNodeErrorsKey, setResetNodeErrorsKey] = React.useState(0);

  React.useEffect(() => setResetNodeErrorsKey((key) => key + 1), [dom]);

  return (
    <AppRoot id={HTML_ID_APP_ROOT}>
      <NoSsr>
        <DomContextProvider value={dom}>
          <AppThemeProvider node={theme}>
            <CssBaseline />
            <ErrorBoundary FallbackComponent={AppError}>
              <ResetNodeErrorsKeyProvider value={resetNodeErrorsKey}>
                <React.Suspense fallback={<AppLoading />}>
                  <JsRuntimeProvider>
                    <AppContextProvider value={appContext}>
                      <QueryClientProvider client={queryClient}>
                        <BrowserRouter basename={basename}>
                          <Routes>
                            <Route path="/" element={<Navigate replace to="/pages" />} />
                            <Route path="/pages" element={<AppOverview dom={dom} />} />
                            {pages.map((page) => (
                              <Route
                                key={page.id}
                                path={`/pages/${page.id}`}
                                element={
                                  <ComponentsContext dom={dom} page={page}>
                                    <RenderedPage nodeId={page.id} />
                                  </ComponentsContext>
                                }
                              />
                            ))}
                          </Routes>
                        </BrowserRouter>
                      </QueryClientProvider>
                    </AppContextProvider>
                  </JsRuntimeProvider>
                </React.Suspense>
              </ResetNodeErrorsKeyProvider>
            </ErrorBoundary>
          </AppThemeProvider>
        </DomContextProvider>
      </NoSsr>
    </AppRoot>
  );
}
Example #27
Source File: PrivateRoute.tsx    From atlas with GNU General Public License v3.0 5 votes vote down vote up
PrivateRoute: React.FC<PrivateRouteProps> = ({ redirectTo, isAuth, element }) => {
  if (!isAuth && redirectTo) {
    return <Navigate to={redirectTo} replace />
  }
  return element
}
Example #28
Source File: App.tsx    From rari-dApp with GNU Affero General Public License v3.0 5 votes vote down vote up
App = memo(() => {
  return (
    <Layout>
      <Routes>
        <Route path="/pools" element={<Outlet />}>
          {Object.values(Pool).map((pool) => {
            return (
              <Route
                key={pool}
                path={pool}
                element={<PoolPortal pool={pool} />}
              />
            );
          })}
        </Route>

        <Route path="/tranches" element={<TranchesPage />} />

        <Route path="/pool2" element={<Pool2Page />} />

        <Route path="/fuse" element={<FusePoolsPage />} />
        <Route path="/fuse/liquidations" element={<FuseLiquidationsPage />} />
        <Route path="/fuse/new-pool" element={<FusePoolCreatePage />} />
        <Route path="/fuse/pool/:poolId" element={<FusePoolPage />} />
        <Route path="/fuse/pool/:poolId/info" element={<FusePoolInfoPage />} />
        <Route path="/fuse/pool/:poolId/edit" element={<FusePoolEditPage />} />

        <Route path="/utils" element={<Navigate to="/" replace={true} />} />
        <Route path="/utils/interest-rates" element={<InterestRatesPage />} />
        <Route path="/utils/positions" element={<StatsPage />} />

        {/* Backwards Compatibility Routes */}
        <Route
          path="/interest_rates"
          element={<Navigate to="/utils/interest-rates" replace={true} />}
        />
        <Route
          path="/interest-rates"
          element={<Navigate to="/utils/interest-rates" replace={true} />}
        />
        <Route
          path="/positions"
          element={<Navigate to="/utils/positions" replace={true} />}
        />
        {/* Backwards Compatibility Routes */}

        <Route path="/" element={<MultiPoolPortal />} />

        <Route path="*" element={<PageNotFound />} />
      </Routes>
    </Layout>
  );
})
Example #29
Source File: RequireSetup.tsx    From raspiblitz-web with MIT License 5 votes vote down vote up
RequireSetup: FC<Props> = ({ needsSetup, children }) => {
  if (!needsSetup) {
    return <Navigate to={"/home"} replace />;
  }

  return children;
}