react-router-dom#StaticRouter TypeScript Examples

The following examples show how to use react-router-dom#StaticRouter. 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: test-utils.tsx    From abacus with GNU General Public License v2.0 7 votes vote down vote up
render: typeof actualRender = <Q extends Queries>(ui: React.ReactElement, options?: RenderOptions<Q>) =>
  actualRender(
    (
      <StaticRouter>
        <ThemeProvider>{ui}</ThemeProvider>
      </StaticRouter>
    ) as React.ReactElement,
    options,
  ) as ReturnType<typeof actualRender>
Example #2
Source File: _app.tsx    From Demae with MIT License 6 votes vote down vote up
Router = ({ location, children }: { location: string, children: any }) => {
	if (process.browser) {
		return (
			<BrowserRouter>
				{children}
			</BrowserRouter>
		)
	} else {
		return (
			<StaticRouter location={location}>
				{children}
			</StaticRouter>
		)
	}
}
Example #3
Source File: Layout.stories.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
withChildren = (): JSX.Element => (
  <StaticRouter>
    <Layout title='Storybook'>
      <div>
        <p>I represent the children.</p>
        <p>
          Because Layout contains Next.js Links, you will find an error in the console due to the rest of Next.js being
          rendered higher in the tree. I do not think it is important enough to find a workaround at this point. So,
          remove this Layout story once real stories for isolated components have been created.
        </p>
      </div>
    </Layout>
  </StaticRouter>
)
Example #4
Source File: Router.tsx    From icejs with MIT License 6 votes vote down vote up
export function IceRouter(props: RouterProps) {
  const { type, routes, fallback, ...others } = props;
  // parse routes before render
  const parsedRoutes = parseRoutes(routes);

  const children = <Routes routes={parsedRoutes} fallback={fallback} />;
  return type === 'static' ?
    <StaticRouter {...others}>
      {children}
    </StaticRouter> :
    <Router {...others}>
      {children}
    </Router>;
}
Example #5
Source File: render.tsx    From cra-serverless with MIT License 6 votes vote down vote up
render = (Tree: React.ElementType, path: string) => {
  const context = { helmet: {} as HelmetData }
  const sheets = new ServerStyleSheet()

  const markup = renderToString(
    sheets.collectStyles(
      <HelmetProvider context={context}>
        <StaticRouter location={path}>
          <Tree />
        </StaticRouter>
      </HelmetProvider>,
    ),
  )

  return html
    .replace('<div id="root"></div>', `<div id="root">${markup}</div>`)
    .replace('<title>React App</title>', context.helmet.title.toString())
    .replace('</head>', `${context.helmet.meta.toString()}</head>`)
    .replace('</head>', `${context.helmet.link.toString()}</head>`)
    .replace('</head>', `${sheets.getStyleTags()}</head>`)
    .replace('<body>', `<body ${context.helmet.bodyAttributes.toString()}>`)
}
Example #6
Source File: pageBuilder.tsx    From react-app-architecture with Apache License 2.0 5 votes vote down vote up
export default function pageBuilder(
  req: PublicRequest,
  pageinfo: PageInfo = {
    title: 'AfterAcademy | React Project',
    description: 'This is the sample project to learn and implement React app.',
  },
  currentState: Partial<RootState> = {},
): string {
  // create mui server style
  const sheets = new ServerStyleSheets();

  const authData = req.universalCookies.get(KEY_AUTH_DATA);
  if (authData?.tokens?.accessToken) {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { tokens, ...data } = authData;
    currentState.authState = {
      data: data, // security
      isLoggingIn: false,
      isLoggingOut: false,
      isLoggedIn: true,
      isForcedLogout: false,
      isRedirectHome: false,
      message: null,
    };
  }

  const store = isDev
    ? configureStore(currentState)
    : createStore(rootReducer, currentState, applyMiddleware(thunk));

  // Render the component to a string
  const html = renderToString(
    sheets.collect(
      <Provider store={store}>
        <CookiesProvider cookies={req.universalCookies}>
          <StaticRouter location={req.url} context={{}}>
            <ThemeProvider theme={theme}>
              <App />
            </ThemeProvider>
          </StaticRouter>
        </CookiesProvider>
      </Provider>,
    ),
  );

  // Grab the CSS from our sheets.
  const css = sheets.toString();

  const baseUrl = `${getProtocol(req)}://${req.get('host')}`;
  const siteUrl = baseUrl + req.originalUrl;

  const { coverImg, title, description } = pageinfo;

  let htmlPage = render({
    html: html,
    css: css,
    preloadedState: store.getState(),
    siteUrl: siteUrl,
    title: title,
    coverImg: coverImg ? coverImg : `${baseUrl}/assets/og-cover-image.jpg`,
    description: description,
  });

  try {
    htmlPage = minifyHtml(htmlPage, {
      minifyCSS: true,
      minifyJS: true,
    });
  } catch (e) {
    console.log(e);
  }

  return htmlPage;
}
Example #7
Source File: ButtonLinks.example.tsx    From hacker-ui with MIT License 5 votes vote down vote up
function ButtonLinksExample(props: Props) {
  const { Root, styles } = useStyles(props);
  const theme = useTheme();

  return (
    <Root>
      <div className={styles.row}>
        <div className={styles.label}>
          This button actually an <code>{'<a>'}</code> tag:
        </div>
        <div className={styles.buttonContainer}>
          <Button
            className={styles.button}
            variant="outlined"
            component="a"
            // @ts-ignore
            href="#"
          >
            Normal Link
          </Button>
        </div>
      </div>

      <div className={styles.row}>
        <div className={styles.label}>
          This button is a <code>{'<Link/>'}</code> from{' '}
          <code>react-router</code>:
        </div>
        <div className={styles.buttonContainer}>
          <StaticRouter>
            <Button
              className={styles.button}
              variant="filled"
              color={theme.brand}
              component={Link}
              // @ts-ignore
              to="/components/buttons-and-links"
            >
              Router Link
            </Button>
          </StaticRouter>
        </div>
      </div>
    </Root>
  );
}
Example #8
Source File: render.tsx    From vanilla-extract with MIT License 5 votes vote down vote up
render = (route: string, headTags: HeadTags) =>
  renderToString(
    <StaticRouter location={route}>
      <HeadProvider headTags={headTags}>
        <App />
      </HeadProvider>
    </StaticRouter>,
  )
Example #9
Source File: Main.tsx    From clearflask with Apache License 2.0 4 votes vote down vote up
render() {
    const Router = (windowIso.isSsr ? StaticRouter : BrowserRouter) as React.ElementType;

    // Redirect www to homepage
    if (windowIso.location.hostname.startsWith('www.')) {
      return (<RedirectIso to={windowIso.location.origin.replace(`www.`, '')} />);
    }

    const isSelfHost = detectEnv() === Environment.PRODUCTION_SELF_HOST;
    const isParentDomain = windowIso.location.hostname === windowIso.parentDomain
      || (!isProd() && windowIso.location.hostname === 'localhost');

    const showSite = isParentDomain && !isSelfHost;
    const showProject = !showSite;
    const showDashboard = isParentDomain || isSelfHost;

    if (showSite || showDashboard) {
      trackingImplicitConsent();
    }

    return (
      <ErrorBoundary showDialog>
        <React.StrictMode>
          <I18nextProvider i18n={this.props.i18n}>
            <StylesProvider injectFirst>
              <MuiThemeProvider theme={this.theme}>
                <MuiSnackbarProvider notistackRef={notistackRef}>
                  <CssBaseline />
                  <ServerErrorNotifier />
                  <CaptchaChallenger />
                  <RemoveSsrCss />
                  <CrowdInInlineEditing />
                  <div style={{
                    minHeight: windowIso.isSsr ? undefined : this.theme.vh(100),
                    display: 'flex',
                    flexDirection: 'column',
                    background: this.theme.palette.background.default,
                  }}>
                    <Router
                      {...(windowIso.isSsr ? {
                        location: this.props.ssrLocation,
                        context: this.props.ssrStaticRouterContext,
                      } : {})}
                    >
                      <ScrollAnchor scrollOnNavigate />
                      <Route path='/' render={routeProps => {
                        trackingBlock(() => {
                          ReactGA.set({ page: routeProps.location.pathname + routeProps.location.search });
                          ReactGA.pageview(routeProps.location.pathname + routeProps.location.search);
                        });
                        return null;
                      }} />
                      <Route render={routeProps => routeProps.location.pathname.startsWith('/embed-status') ? null : (
                        <EnvironmentNotifier key='env-notifier' />
                      )} />
                      <Switch>
                        {[
                          (
                            <Route key='api-docs' path='/api' render={props => (
                              <NoSsr>
                                <ApiDocs />
                              </NoSsr>
                            )} />
                          ),
                          ...(!isProd() ? [(
                            <Route key='mock-oauth-provider-bathtub' path='/bathtub/authorize' render={props => (
                              <Provider store={ServerAdmin.get().getStore()}>
                                <BathtubOauthProvider />
                              </Provider>
                            )} />
                          )] : []),
                          ...(showDashboard ? [(
                            <Route key='dashboard' path="/dashboard/:path?/:subPath*" render={props => (
                              <Provider store={ServerAdmin.get().getStore()}>
                                <SentryIdentifyAccount />
                                <SetMaxAge val={0 /* If you want to cache, don't cache if auth is present in URL */} />
                                <NoSsr>
                                  <Dashboard {...props} />
                                </NoSsr>
                                <IntercomWrapperMain suppressBind />
                                <HotjarWrapperMain />
                              </Provider>
                            )} />
                          ), (
                            <Route key='invoice' path="/invoice/:invoiceId" render={props => (
                              <Provider store={ServerAdmin.get().getStore()}>
                                <SentryIdentifyAccount />
                                <SetMaxAge val={0} />
                                <Invoice invoiceId={props.match.params['invoiceId']} />
                              </Provider>
                            )} />
                          ), (
                            <Route key='enter' exact path='/:type(login|signup|invitation|coupon)/:id([a-z0-9]*)?' render={props => (
                              <Provider store={ServerAdmin.get().getStore()}>
                                <SetMaxAge val={0} />
                                <SetTitle title={props.match.params['type'] === 'login'
                                  ? 'Login'
                                  : (props.match.params['type'] === 'signup'
                                    ? 'Sign up'
                                    : (props.match.params['type'] === 'invitation'
                                      ? 'Invitation'
                                      : 'Coupon'))} />
                                <AccountEnterPage
                                  type={props.match.params['type']}
                                  invitationId={props.match.params['type'] === 'invitation' ? props.match.params['id'] : undefined}
                                  couponId={props.match.params['type'] === 'coupon' ? props.match.params['id'] : undefined}
                                />
                              </Provider>
                            )} />
                          )] : []),
                          ...(showProject ? [(
                            <Route key='embed-status' path="/embed-status/post/:postId" render={props => (
                              <>
                                <SetMaxAge val={24 * 60 * 60} />
                                <PostStatus
                                  {...props}
                                  postId={props.match.params['postId'] || ''}
                                />
                              </>
                            )} />
                          ), (
                            <Route key='app' path='/' render={props => (
                              <>
                                <SetMaxAge val={60} />
                                <App slug={windowIso.location.hostname} {...props} />
                              </>
                            )} />
                          )] : []),
                          ...(showSite ? [(
                            <Route key='site' path='/' render={props => (
                              <Provider store={ServerAdmin.get().getStore()}>
                                <SentryIdentifyAccount />
                                <SetMaxAge val={24 * 60 * 60} />
                                <Site {...props} />
                                <IntercomWrapperMain />
                                <HotjarWrapperMain />
                              </Provider>
                            )} />
                          )] : []),
                        ]}
                      </Switch>
                    </Router>
                  </div>
                </MuiSnackbarProvider>
              </MuiThemeProvider>
            </StylesProvider>
          </I18nextProvider>
        </React.StrictMode>
      </ErrorBoundary>
    );
  }