react-router#Switch TypeScript Examples

The following examples show how to use react-router#Switch. 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: BaseRoute.tsx    From electron with MIT License 6 votes vote down vote up
PackingWithAuth: React.FC<{ onChange?: PackingWithAuthOnChange }> = ({ children, onChange }) => {
  const _onChange = (from: string, to: string, next: (path: Path, state?: LocationState) => void) => {
    /** if ('登录状态失效') { message.success('登录状态失效,请重新登录'); next('/login') } */
  };
  return (
    <BaseRouteChange onChange={onChange || _onChange}>
      <Suspense fallback={<RouterWrapSpin />}>
        <Switch>
          {children}
          <Route path="*" component={RouterWrapNotFound}></Route>
        </Switch>
      </Suspense>
    </BaseRouteChange>
  );
}
Example #2
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function Selection ({ basePath, onAdd }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();

  const itemsRef = useRef([
    {
      isRoot: true,
      name: 'modules',
      text: t<string>('Storage')
    },
    {
      name: 'constants',
      text: t<string>('Constants')
    },
    {
      name: 'raw',
      text: t<string>('Raw storage')
    }
  ]);

  const _onAdd = useCallback(
    (query: ParitalQueryTypes): void => onAdd({ ...query, id: ++id }),
    [onAdd]
  );

  return (
    <>
      <Tabs
        basePath={basePath}
        items={itemsRef.current}
      />
      <Switch>
        <Route path={`${basePath}/constants`}><Consts onAdd={_onAdd} /></Route>
        <Route path={`${basePath}/raw`}><Raw onAdd={_onAdd} /></Route>
        <Route><Modules onAdd={_onAdd} /></Route>
      </Switch>
    </>
  );
}
Example #3
Source File: index.tsx    From homebase-app with MIT License 6 votes vote down vote up
StepRouter: React.FC = () => {
  const match = useRouteMatch();

  return (
    <ProtectedRoute>
      <Switch>
        <Route path={`${match.url}/dao`}>
          <AnalyticsWrappedStep name="DAO Settings" index={0}>
            <DaoSettings />
          </AnalyticsWrappedStep>
        </Route>
        <Route path={`${match.url}/voting`}>
          <AnalyticsWrappedStep name="Governance" index={1}>
            <Governance />
          </AnalyticsWrappedStep>
        </Route>
        <Route path={`${match.url}/quorum`}>
          <AnalyticsWrappedStep name="Quorum" index={2}>
            <Quorum />
          </AnalyticsWrappedStep>
        </Route>
        <Route path={`${match.url}/summary`}>
          <AnalyticsWrappedStep name="Summary" index={3}>
            <Summary />
          </AnalyticsWrappedStep>
        </Route>
        <Route path={`${match.url}/review`}>
          <AnalyticsWrappedStep name="Deployment" index={4}>
            <Review />
          </AnalyticsWrappedStep>
        </Route>
        <Redirect to={`${match.url}/dao`} />
      </Switch>
    </ProtectedRoute>
  );
}
Example #4
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function SigningApp ({ basePath }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();

  const itemsRef = useRef([
    {
      isRoot: true,
      name: 'sign',
      text: t<string>('Sign message')
    },
    {
      name: 'verify',
      text: t<string>('Verify signature')
    },
    {
      name: 'hash',
      text: t<string>('Hash data')
    }
  ]);

  return (
    <main className='toolbox--App'>
      <Tabs
        basePath={basePath}
        items={itemsRef.current}
      />
      <Switch>
        <Route path={`${basePath}/hash`}><Hash /></Route>
        <Route path={`${basePath}/verify`}><Verify /></Route>
        <Route><Sign /></Route>
      </Switch>
    </main>
  );
}
Example #5
Source File: AppsPage.tsx    From disco-cube-admin with MIT License 6 votes vote down vote up
AppsPage: React.FC<Props> = ({}) => {
  const match = useRouteMatch();

  return (
    <Page>
      <Switch>
        <Route exact path={match.path}>
          <ConnectedAppsPageContent />
        </Route>
        {Object.entries(apps).map(([key, { path, render }]) => (
          <Route key={key} path={`${match.path}${path}`}>
            {render()}
          </Route>
        ))}
      </Switch>
    </Page>
  );
}
Example #6
Source File: merchants.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function MerchantsApp ({ basePath, onStatusChange }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const { hasAccounts } = useAccounts();
  const { isIpfs } = useIpfs();
  const { systemChain } = useApi();
  const isMaxwell = systemChain === 'Crust Maxwell';

  const itemsRef = useRef([
    {
      isRoot: true,
      name: 'overview',
      text: t<string>('My merchants')
    }
  ]);

  return (
    <main className='accounts--App'>
      <HelpOverlay md={basicMd as string} />
      <header>
        <Tabs
          basePath={basePath}
          hidden={(hasAccounts && !isIpfs) ? undefined : HIDDEN_ACC}
          items={itemsRef.current}
        />
      </header>
      <Switch>
        <Route basePath={basePath}
          onStatusChange={onStatusChange}>
          { isMaxwell ? <Merchants/> : <MainnetMarchants/>}
        </Route>

      </Switch>
    </main>
  );
}
Example #7
Source File: index.tsx    From tailchat with GNU General Public License v3.0 6 votes vote down vote up
PanelRoute: React.FC = React.memo(() => {
  useRecordMeasure('AppRouteRenderStart');

  return (
    <div className="flex h-full bg-content-light dark:bg-content-dark">
      <MainProvider>
        <Switch>
          <Route
            exact={true}
            path="/panel/personal/converse/:converseId"
            component={PersonalConverse}
          />
          <Route
            exact={true}
            path="/panel/group/:groupId/detail"
            render={(props) => (
              <GroupDetail
                groupId={props.match.params.groupId}
                onClose={() => {}}
              />
            )}
          />
          <Route
            exact={true}
            path="/panel/group/:groupId/:panelId"
            component={GroupPanelRoute}
          />

          <Route>{t('未知的面板')}</Route>
        </Switch>
      </MainProvider>
    </div>
  );
})
Example #8
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function GiltApp ({ basePath, className }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();

  const tabsRef = useRef([
    {
      isRoot: true,
      name: 'overview',
      text: t<string>('Overview')
    }
  ]);

  return (
    <main className={className}>
      <Tabs
        basePath={basePath}
        items={tabsRef.current}
      />
      <Switch>
        <Route>
          <Overview />
        </Route>
      </Switch>
    </main>
  );
}
Example #9
Source File: AppRoutes.tsx    From whiteboard-demo with MIT License 6 votes vote down vote up
public render(): React.ReactNode {
        return (
            <Router history={history}>
                <Switch>
                    <Route path="/replay/:identity/:uuid/:userId/:region" component={ReplayPage} />
                    <Route path="/replay-video/:identity/:uuid/:userId/:region" component={ReplayVideoPage} />
                    <Route path="/whiteboard/:identity/:uuid/:userId/:region" component={WhiteboardPage} />
                    <Route path="/whiteboard/:identity/:uuid/:region" component={WhiteboardCreatorPage} />
                    <Route path="/history/" component={HistoryPage} />
                    <Route path="/join/" component={JoinPage}/>
                    <Route path="/create/" component={CreatePage}/>
                    <Route path="/name/:uuid?/" component={AddNamePage}/>
                    <Route path="/storage/" component={Storage}/>
                    <Route path="/" component={IndexPage}/>
                </Switch>
            </Router>
      );
    }
Example #10
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function DemocracyApp ({ basePath }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const dispatchCount = useDispatchCounter();

  const items = useMemo(() => [
    {
      isRoot: true,
      name: 'overview',
      text: t<string>('Overview')
    },
    {
      count: dispatchCount,
      name: 'dispatch',
      text: t<string>('Dispatch')
    }
  ], [dispatchCount, t]);

  return (
    <main className='democracy--App'>
      <HelpOverlay md={basicMd as string} />
      <Tabs
        basePath={basePath}
        items={items}
      />
      <Switch>
        <Route path={`${basePath}/dispatch`}>
          <Execute />
        </Route>
        <Route><Overview /></Route>
      </Switch>
    </main>
  );
}
Example #11
Source File: index.tsx    From oasis-wallet-web with Apache License 2.0 6 votes vote down vote up
export function OpenWalletPage(props: Props) {
  return (
    <TransitionGroup>
      <Switch>
        <TransitionRoute exact path="/open-wallet" component={SelectOpenMethod} />
        <TransitionRoute exact path="/open-wallet/mnemonic" component={FromMnemonic} />
        <TransitionRoute exact path="/open-wallet/private-key" component={FromPrivateKey} />
        <TransitionRoute exact path="/open-wallet/ledger" component={FromLedger} />
      </Switch>
    </TransitionGroup>
  )
}
Example #12
Source File: App.tsx    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
App: VFC = () => {
  const { hash, pathname } = useLocation();
  const { action } = useHistory();

  useEffect(() => {
    if (!hash || action !== 'POP') {
      window.scrollTo(0, 0);
    }
  }, [action, hash, pathname]);

  return (
    <div className="container">
      <Switch>
        <Route exact path="/">
          <Home />
        </Route>
        <Route path="/characters" component={Characters} />
        <Redirect to="/" />
      </Switch>
    </div>
  );
}
Example #13
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function BridgeApp ({ basePath, onStatusChange }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const { hasAccounts } = useAccounts();
  const { isIpfs } = useIpfs();

  const itemsRef = useRef([
    {
      isRoot: true,
      name: 'candy',
      text: t<string>('My Candy')
    }
  ]);

  return (
    <main className='accounts--App'>
      <header>
        <Tabs
          basePath={basePath}
          hidden={(hasAccounts && !isIpfs) ? undefined : HIDDEN_ACC}
          items={itemsRef.current}
        />
      </header>
      <Switch>
        <Route basePath={basePath}
          onStatusChange={onStatusChange}>
          <CandyAssets />
        </Route>

      </Switch>
    </main>
  );
}
Example #14
Source File: Characters.tsx    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
Characters: VFC<RouteComponentProps> = ({ match }) => (
  <>
    <header>
      <h1>『SLAM DUNK』登場人物</h1>
    </header>
    <Switch>
      <Route exact path={`${match.path}`}>
        <AllCharacters />
      </Route>
      <Route path={`${match.path}/:schoolCode`}>
        <SchoolCharacters />
      </Route>
      <Redirect to="/" />
    </Switch>
    <Divider hidden />
    <HomeButton />
  </>
)
Example #15
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function AddressesApp ({ basePath, onStatusChange }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();

  const itemsRef = useRef([
    {
      isRoot: true,
      name: 'contacts',
      text: t<string>('My contacts')
    }
  ]);

  return (
    <main>
      <Tabs
        basePath={basePath}
        items={itemsRef.current}
      />
      <Switch>
        <Route>
          <Contacts
            basePath={basePath}
            onStatusChange={onStatusChange}
          />
        </Route>
      </Switch>
    </main>
  );
}
Example #16
Source File: entry.tsx    From atorch-console with MIT License 6 votes vote down vote up
Entry: React.FC = () => (
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Switch>
        <Route exact path='/' component={AtorchConsole} />
      </Switch>
    </ConnectedRouter>
  </Provider>
)
Example #17
Source File: Entry.tsx    From mops-vida-pm-watchdog with MIT License 6 votes vote down vote up
Entry: React.FC = () => (
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Switch>
        <Route exact path='/' component={SensorConsole} />
      </Switch>
    </ConnectedRouter>
  </Provider>
)
Example #18
Source File: App.tsx    From msteams-meetings-template with MIT License 6 votes vote down vote up
function App() {
  return (
    <Provider store={store}>
      <ConnectedRouter history={hist}>
        <Switch>
          <Route exact path="/signin" component={SigninPage} />
          <Route exact path="/createMeeting" component={MeetingPage} />
          <Route exact path="/copyMeeting" component={CopyMeetingPage} />
          <Route exact path="/error" component={ErrorPage} />
          <Route component={CreateLandingPage} />
        </Switch>
      </ConnectedRouter>
    </Provider>
  );
}
Example #19
Source File: app.tsx    From remote-office-hours-queue with Apache License 2.0 6 votes vote down vote up
function App(props: AppProps) {
    useGoogleAnalytics(props.globals.ga_tracking_id, props.globals.debug);
    return (
        <Switch>
            <Route path='/' exact render={p => 
                <HomePage {...p} user={props.globals.user} loginUrl={props.globals.login_url} backends={props.globals.backends} defaultBackend={props.globals.default_backend} />
            }/>
            <Route path='/manage' exact render={p => 
                <ManagePage {...p} user={props.globals.user} loginUrl={props.globals.login_url} backends={props.globals.backends} defaultBackend={props.globals.default_backend} />
            }/>
            <Route path='/manage/:queue_id' exact render={p => 
                <QueueManagerPage {...p} user={props.globals.user} loginUrl={props.globals.login_url} backends={props.globals.backends} key={(p.match.params as any).queue_id} defaultBackend={props.globals.default_backend} />
            }/>
            <Route path='/queue/:queue_id' exact render={p => 
                <QueuePage {...p} user={props.globals.user} loginUrl={props.globals.login_url} backends={props.globals.backends} key={(p.match.params as any).queue_id} defaultBackend={props.globals.default_backend} />
            }/>
            <Route path='/search/:term' exact render={p =>
                <SearchPage {...p} user={props.globals.user} loginUrl={props.globals.login_url} backends={props.globals.backends} defaultBackend={props.globals.default_backend} />
            }/>
            <Route path='/preferences' exact render={p =>
                <PreferencesPage {...p} user={props.globals.user} loginUrl={props.globals.login_url} backends={props.globals.backends} defaultBackend={props.globals.default_backend} />
            }/>
            <Route path='/add_queue' exact render={p =>
                <AddQueuePage {...p} user={props.globals.user} loginUrl={props.globals.login_url} backends={props.globals.backends} defaultBackend={props.globals.default_backend} />
            }/>
            <Route path='/manage/:queue_id/settings' exact render={p =>
                <ManageQueueSettingsPage {...p} user={props.globals.user} loginUrl={props.globals.login_url} backends={props.globals.backends} defaultBackend={props.globals.default_backend} />
            }/>
        </Switch>
    );
}
Example #20
Source File: Environments.context.tsx    From app-stormkit-io with GNU General Public License v3.0 6 votes vote down vote up
EnvironmentsContext: React.FC<ContextProps> = ({
  environments,
}): React.ReactElement => {
  return (
    <Context.Provider value={{ environments }}>
      <Switch>
        {routes.map(route => (
          <Route
            {...route}
            key={Array.isArray(route.path) ? route.path[0] : route.path}
          />
        ))}
      </Switch>
    </Context.Provider>
  );
}
Example #21
Source File: App.tsx    From Full-Stack-React-TypeScript-and-Node with MIT License 6 votes vote down vote up
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <Switch>
          <Route exact={true} path="/" component={Home}></Route>
          <Route path="/another" component={AnotherScreen}></Route>
        </Switch>
      </header>
    </div>
  );
}
Example #22
Source File: App.tsx    From useDApp with MIT License 6 votes vote down vote up
export function App() {
  return (
    <Page>
      <GlobalStyle />
      <BrowserRouter>
        <NavBar />
        <Switch>
          <Route exact path="/balance" component={Balance} />
          <Route exact path="/prices" component={Prices} />
          <Route exact path="/ens" component={ENSExample} />
          <Route exact path="/block" component={Block} />
          <Route exact path="/tokens" component={Tokens} />
          <Route exact path="/send" component={SendEtherPage} />
          <Route exact path="/transactions" component={Transactions} />
          <Route exact path="/web3modal" component={Web3Modal} />
          <Route exact path="/web3react" component={Web3ReactConnector} />
          <Route exact path="/multichain" component={Multichain} />
          <Route exact path="/wallet-connect" component={WalletConnect} />
          <Redirect exact from="/" to="/balance" />
        </Switch>
      </BrowserRouter>
      <NotificationsList />
    </Page>
  )
}
Example #23
Source File: App.tsx    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
function AppComponent(props: { history: History }): React.ReactElement {
  return (
    <ConnectedRouter history={props.history}>
      <Head />
      <Layout history={props.history}>
        <AppAlertGroup />
        <Suspense fallback={Fallback}>
          <Switch>
            <Routes />
            <Redirect path='*' to='/' />
          </Switch>
        </Suspense>
      </Layout>
    </ConnectedRouter>
  );
}
Example #24
Source File: AnimatedRoutes.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
AnimatedPageSwitch = connect<ConnectProps, {}, Props, ReduxState>((state) => {
  return {
    customPageSlugs: state.conf.conf && state.conf.conf.layout.pages.map(p => p.slug),
  }
})((props: PropsWithChildren<Props & ConnectProps>) => {
  const children = [
    props.children,
    ...(props.customPageSlugs || []).filter(pageSlug => !!pageSlug).map(customPageSlug => props.render(customPageSlug)),
    props.render(''),
    props.notFoundRoute,
  ];
  return props.theme.disableTransitions
    ? <Switch>{children}</Switch>
    : <MuiAnimatedSwitch>{children}</MuiAnimatedSwitch>;
})
Example #25
Source File: App.tsx    From cra-serverless with MIT License 6 votes vote down vote up
App: React.FC = () => (
  <>
    <GlobalStyles />

    <Helmet>
      <title>{process.env.REACT_APP_NAME}</title>
    </Helmet>

    <Wrapper>
      <Navigation />

      <Switch>
        <Route path="/details/:id" component={Details} />
        <Route path="/" component={Home} exact />

        <Route component={NotFound} />
      </Switch>

      <Footer />
    </Wrapper>
  </>
)
Example #26
Source File: RightSidebar.tsx    From revite with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function RightSidebar() {
    const [sidebar, setSidebar] = useState<"search" | undefined>();
    const close = () => setSidebar(undefined);

    useEffect(
        () =>
            internalSubscribe(
                "RightSidebar",
                "open",
                setSidebar as (...args: unknown[]) => void,
            ),
        [setSidebar],
    );

    const content =
        sidebar === "search" ? (
            <SearchSidebar close={close} />
        ) : (
            <MemberSidebar />
        );

    return (
        <SidebarBase>
            <Switch>
                <Route path="/server/:server/channel/:channel">{content}</Route>
                <Route path="/channel/:channel">{content}</Route>
            </Switch>
        </SidebarBase>
    );
}
Example #27
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function GiltApp ({ basePath, className }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();

  const tabsRef = useRef([
    {
      isRoot: true,
      name: 'overview',
      text: t<string>('Overview')
    }
  ]);

  return (
    <main className={className}>
      <Tabs
        basePath={basePath}
        items={tabsRef.current}
      />
      <Switch>
        <Route>
          <Overview />
        </Route>
      </Switch>
    </main>
  );
}
Example #28
Source File: Wizard.tsx    From twilio-voice-notification-app with Apache License 2.0 5 votes vote down vote up
Wizard = ({ data, activeStep }: StepProps) => {
  // Info about completition status of each step.
  const stepsCompletion = useSelector(stepsCompletionSelector);

  return (
    <Box>
      <Stepper
        activeStep={activeStep && routerSteps.indexOf(activeStep)}
        alternativeLabel
        connector={<CustomConnector />}
        style={{ backgroundColor: 'transparent' }}
      >
        {routerSteps.map((step) => {
          const { label } = step;
          const completed =
            !isStepAhead(activeStep, step) && stepsCompletion[step.key];

          return (
            <Step key={label} disabled={true}>
              <StepButton
                icon={
                  <WizardStepIcon
                    icon={step.icon}
                    active={activeStep === step}
                    completed={completed}
                  />
                }
              >
                <StyledStepLabel>{label}</StyledStepLabel>
              </StepButton>
            </Step>
          );
        })}
      </Stepper>
      <Switch>
        {routerSteps.map((step) => (
          <Route
            key={step.key}
            path={step.location}
            render={() => React.createElement(step.component, { step, data })}
          />
        ))}
        <Redirect from="*" to="/create/configure" />
      </Switch>
    </Box>
  );
}
Example #29
Source File: ProfileRouter.tsx    From frontegg-react with MIT License 5 votes vote down vote up
ProfileRouter: FC<BasePageProps> = (props) => {
  const { verified } = useAuthUser();
  const [rootPath, isRootPathContext] = useRootPath(props, '/profile');
  reloadProfileIfNeeded();

  const children = props.children ?? (
    <>
      <ProfileInfoPage key='ProfileInfoPage' />,
      <ProfilePasswordSettingsPage key='ProfilePasswordSettingsPage' />,
      <ProfileMfaPage key='ProfileMfaPage' />,
    </>
  );

  const [defaultTabs, invalidTabs] = buildTabsFromChildren(rootPath, children);
  invalidTabs.length > 0 &&
    logger.error(`Children at positions [${invalidTabs.join(', ')}] should implement ProfilePage interface.`);

  if (!isRootPathContext) {
    return <RootPathContext.Provider value={rootPath}>{children}</RootPathContext.Provider>;
  }

  const tabs = defaultTabs.map((tab) => {
    if (!verified && tab.route.includes('password')) return { ...tab, disabled: true };
    return tab;
  });

  return (
    <>
      <ProfileTabs tabs={tabs} />
      <Switch>
        {tabs.map((tab: any) => (
          <Route exact key={tab.route} path={tab.route}>
            {tab.comp}
          </Route>
        ))}
        <Redirect from='*' to={tabs?.[0]?.route ?? '/'} />
      </Switch>
    </>
  );
}