react-router#Route TypeScript Examples

The following examples show how to use react-router#Route. 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: routerUtil.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
// React-Router Redirect component (within domain)
export function RedirectIso(props: { to: string, httpCode?: number }) {
  return (
    <Route
      render={({ staticContext }) => {
        if (windowIso.isSsr && staticContext) {
          (staticContext as StaticRouterContext).statusCode = props.httpCode || 302;
          (staticContext as StaticRouterContext).url = props.to;
        }
        return <Redirect to={props.to} />;
      }}
    />
  );
}
Example #2
Source File: Router.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
Router = (_props: Props) => {
  const { entity } = useEntity();

  if (!isJenkinsAvailable(entity)) {
    return <MissingAnnotationEmptyState annotation={JENKINS_ANNOTATION} />;
  }

  return (
    <Routes>
      <Route path="/" element={<CITable />} />
      <Route path={`/${buildRouteRef.path}`} element={<DetailedViewPage />} />
    </Routes>
  );
}
Example #3
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 #4
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 #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: Router.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
Router = ({ entity }: { entity: Entity }) => {
  return (
    <Routes>
      <Route
        path="/"
        element={
          <SentryIssuesWidget
            entity={entity}
            statsFor="24h"
            tableOptions={{
              padding: 'dense',
              paging: true,
              search: false,
              pageSize: 5,
            }}
          />
        }
      />
      )
    </Routes>
  );
}
Example #7
Source File: SettingsPage.tsx    From lightning-terminal with MIT License 6 votes vote down vote up
SettingsPage: React.FC = () => {
  const { Wrapper } = Styled;

  return (
    <Wrapper>
      <Routes>
        <Route path="/" element={<GeneralSettings />} />
        <Route path="unit" element={<UnitSettings />} />
        <Route path="balance" element={<BalanceSettings />} />
        <Route path="explorers" element={<ExplorerSettings />} />
      </Routes>
    </Wrapper>
  );
}
Example #8
Source File: App.tsx    From axios-source-analysis with MIT License 6 votes vote down vote up
function App() {
  debugger
  return (
    <Routes>
      {/* 注意,这里不是LayoutRoute,因为LayoutRoute只允许element和children,而这里有path */}
      <Route path='/' element={<Layout />}>
        {
          routeConfigs.map(({ path, Element }) => <Route key={path} path={`${path}${path === '*' ? '': '/*'}`} element={<Element />} />)
        }
      </Route>
    </Routes>
  )
}
Example #9
Source File: Routes.tsx    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
function Routes(): React.ReactElement {
  const routes = items.map(item => (
    <Route exact
      key={item.to}
      path={item.to}
      component={item.component}
    />
  ));
  return (
    <React.Fragment>
      {routes}
    </React.Fragment>
  );
}
Example #10
Source File: CustomerExternalTrackers.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
render() {
    if (this.props.googleAnalytics && !this.gaInitialized) {
      this.gaInitialize(this.props.googleAnalytics.trackingCode);
      this.gaInitialized = true;
    }
    return (
      <>
        <HotjarWrapperCustomer />
        {this.props.googleAnalytics && (
          <Route path='/' render={routeProps => {
            trackingBlock(() => {
              ReactGA.ga(`${CustomerTrackerName}.set`, 'page', routeProps.location.pathname + routeProps.location.search);
              ReactGA.ga(`${CustomerTrackerName}.send`, 'pageview', { 'page': routeProps.location.pathname + routeProps.location.search });
            });
            return null;
          }} />
        )}
      </>
    );
  }
Example #11
Source File: PermissionedRoute.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
PermissionedRoute = (
  props: ComponentProps<typeof Route> & {
    errorComponent?: ReactElement | null;
  } & (
      | {
          permission: Exclude<Permission, ResourcePermission>;
          resourceRef?: never;
        }
      | {
          permission: ResourcePermission;
          resourceRef: string | undefined;
        }
    ),
) => {
  const { permission, resourceRef, errorComponent, ...otherProps } = props;

  const permissionResult = usePermission(
    isResourcePermission(permission)
      ? { permission, resourceRef }
      : { permission },
  );
  const app = useApp();
  const { NotFoundErrorPage } = app.getComponents();

  let shownElement: ReactElement | null | undefined =
    errorComponent === undefined ? <NotFoundErrorPage /> : errorComponent;

  if (permissionResult.loading) {
    shownElement = null;
  } else if (permissionResult.allowed) {
    shownElement = props.element;
  }

  return <Route {...otherProps} element={shownElement} />;
}
Example #12
Source File: EpiSpaRouter.tsx    From foundation-lib-spa-core with Apache License 2.0 6 votes vote down vote up
function createRouteNode(route: IRouteConfigItem, basePath = "", key ?: string, ctx ?: IEpiserverContext) : React.ReactElement<RouteProps> {
    
    let createdRoute : string = basePath ? (basePath.substr(-1) === "/" ? basePath.substr(0, -1) : basePath) : "";
    createdRoute = createdRoute + "/" + (route.path ? (route.path.substr(0,1) === "/" ? route.path.substr(1) : route.path) : "")

    if (ctx?.isDebugActive()) console.log('Generating Route Virtual DOM Node', createdRoute, route, key);

    const newRouteProps : RouteProps = {
        children: route.children,
        exact: route.exact,
        location: route.location,
        path: createdRoute,
        sensitive: route.sensitive,
        strict: route.strict,
        render: route.render ? (props: RouteComponentProps) => { return route.render ? route.render({ ...props, routes: route.routes, path: route.path }) : <div/> } : undefined,
        component: route.component ? (props: RouteComponentProps) => { const RouteComponent = route.component || 'div'; return <RouteComponent { ...props } routes={ route.routes } path={ route.path } />} : undefined
    }
    return <Route { ...newRouteProps } key={ key } />
}
Example #13
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 #14
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 #15
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 #16
Source File: ProtectedRoute.tsx    From flame with MIT License 6 votes vote down vote up
ProtectedRoute = ({ ...rest }: RouteProps) => {
  const { isAuthenticated } = useSelector((state: State) => state.auth);

  if (isAuthenticated) {
    return <Route {...rest} />;
  } else {
    return <Redirect to="/settings/app" />;
  }
}
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: 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 #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 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 #24
Source File: Button.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
describe('<Button />', () => {
  it('navigates using react-router', async () => {
    const testString = 'This is test string';
    const buttonLabel = 'Navigate!';
    const { getByText } = render(
      wrapInTestApp(
        <Routes>
          <Route path="/test" element={<p>{testString}</p>} />
          <Button to="/test">{buttonLabel}</Button>
        </Routes>,
      ),
    );

    expect(() => getByText(testString)).toThrow();
    await act(async () => {
      fireEvent.click(getByText(buttonLabel));
    });
    expect(getByText(testString)).toBeInTheDocument();
  });
});
Example #25
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 #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: App.tsx    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
App: VFC = () => (
  <>
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/:orgCode/members" element={<Members />} />
      <Route path="*" element={<Navigate to="/" />} />
    </Routes>
  </>
)
Example #28
Source File: TabbedLayout.stories.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
Default = () => (
  <Wrapper>
    <TabbedLayout>
      <TabbedLayout.Route path="/" title="tabbed-test-title">
        <div>tabbed-test-content</div>
      </TabbedLayout.Route>
      <TabbedLayout.Route path="/some-other-path" title="tabbed-test-title-2">
        <div>tabbed-test-content-2</div>
      </TabbedLayout.Route>
    </TabbedLayout>
  </Wrapper>
)
Example #29
Source File: App.tsx    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
App: VFC = () => (
  <>
    <Switch>
      <Route path="/" exact component={Home} />
      <Route path="/:orgCode/members" component={Members} />
      <Redirect to="/" />
    </Switch>
  </>
)