react-router#match TypeScript Examples

The following examples show how to use react-router#match. 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: TestUtils.tsx    From kfp-tekton-backend with Apache License 2.0 7 votes vote down vote up
/**
   * Generates a customizable PageProps object that can be passed to initialize
   * Page components, taking care of setting ToolbarProps properly, which have
   * to be set after component initialization.
   */
  // tslint:disable-next-line:variable-name
  public static generatePageProps(
    PageElement: new (_: PageProps) => Page<any, any>,
    location: Location,
    matchValue: match,
    historyPushSpy: jest.SpyInstance<unknown> | null,
    updateBannerSpy: jest.SpyInstance<unknown> | null,
    updateDialogSpy: jest.SpyInstance<unknown> | null,
    updateToolbarSpy: jest.SpyInstance<unknown> | null,
    updateSnackbarSpy: jest.SpyInstance<unknown> | null,
  ): PageProps {
    const pageProps = {
      history: { push: historyPushSpy } as any,
      location: location as any,
      match: matchValue,
      toolbarProps: { actions: {}, breadcrumbs: [], pageTitle: '' },
      updateBanner: updateBannerSpy as any,
      updateDialog: updateDialogSpy as any,
      updateSnackbar: updateSnackbarSpy as any,
      updateToolbar: updateToolbarSpy as any,
    } as PageProps;
    pageProps.toolbarProps = new PageElement(pageProps).getInitialToolbarState();
    // The toolbar spy gets called in the getInitialToolbarState method, reset it
    // in order to simplify tests
    if (updateToolbarSpy) {
      updateToolbarSpy.mockReset();
    }
    return pageProps;
  }
Example #2
Source File: SelectedChannel.tsx    From js-ts-monorepos with BSD 2-Clause "Simplified" License 6 votes vote down vote up
SelectedChannel: React.FunctionComponent<{
  match: match<{ channelId: string }>;
  channels: IChannel[];
}> = ({ match, channels }) => {
  if (!channels) throw new Error("no channels");
  if (!match) throw new Error("no match");

  const { params } = match;
  if (!match) return <p>No match params</p>;
  const { channelId: selectedChannelId } = params;
  if (!selectedChannelId) return <p>Invalid channelId</p>;
  const selectedChannel = channels.find(
    (c: IChannel) => c.id === selectedChannelId
  );
  if (!selectedChannel)
    return (
      <div>
        <p>Could not find channel with id {selectedChannelId}</p>
        <pre>{JSON.stringify(channels, null, "  ")}</pre>
      </div>
    );

  return <Channel channel={selectedChannel} />;
}
Example #3
Source File: SelectedTeam.tsx    From js-ts-monorepos with BSD 2-Clause "Simplified" License 6 votes vote down vote up
SelectedTeam: React.FunctionComponent<{
  match: match<{ teamId: string }>;
  teams: ITeam[];
}> = ({ match, teams }) => {
  if (!match) throw new Error("no match");

  const { params } = match;
  if (!params) throw new Error("no match params");

  const { teamId: selectedTeamId } = params;
  if (!selectedTeamId) throw new Error(`undefined teamId`);

  const selectedTeam = teams.find((t: ITeam) => t.id === selectedTeamId);
  if (!selectedTeam)
    throw new Error(`Invalid could not find team with id {selectedTeamId}`);

  return <Team team={selectedTeam} />;
}
Example #4
Source File: App.tsx    From clearflask with Apache License 2.0 5 votes vote down vote up
pageChanged(pageUrlName: string): void {
    this.props.history.push(`${this.props.match.url}${pageUrlName}`);
  }
Example #5
Source File: amount.spec.tsx    From bitpay-browser-extension with MIT License 4 votes vote down vote up
describe('Amount Page', () => {
  let path: string;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  let history: any;
  let matchObj: match<{ id: string }>;
  let location;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  let wrapper: any;
  beforeEach(() => {
    path = '/amount/:brand';
    history = createMemoryHistory();

    matchObj = {
      isExact: false,
      path,
      url: path.replace(':brand', 'amazon'),
      params: { id: 'amazon' }
    };
    location = createLocation(path, { cardConfig: CardConfigData, merchant: MerchantData });

    wrapper = shallow(
      <Amount
        clientId={AmountProps.clientId}
        email={AmountProps.email}
        purchasedGiftCards={AmountProps.purchasedGiftCards}
        setPurchasedGiftCards={AmountProps.setPurchasedGiftCards}
        history={history}
        location={location}
        match={matchObj}
      />
    );
  });

  it('should create the component', () => {
    expect(wrapper.exists()).toBeTruthy();
  });

  it('should validate input value', () => {
    const inputText = [
      { value: 'alphabetic', expectedInputVal: '', expectedInputDivVal: '0' },
      { value: '12', expectedInputVal: '12', expectedInputDivVal: '12' },
      { value: '40.013', expectedInputVal: '40.01', expectedInputDivVal: '40.01' },
      { value: '200.11', expectedInputVal: '200.11', expectedInputDivVal: '200.11' },
      { value: '0.11', expectedInputVal: '0.11', expectedInputDivVal: '0.11' },
      { value: '4000', expectedInputVal: '', expectedInputDivVal: '0' },
      { value: '#$%12', expectedInputVal: '12', expectedInputDivVal: '12' },
      { value: 'alpha%12', expectedInputVal: '12', expectedInputDivVal: '12' }
    ];
    inputText.forEach(val => {
      const input = wrapper.find('input');
      input.simulate('change', { currentTarget: { value: val.value } });
      expect(wrapper.find('input').prop('value')).toBe(val.expectedInputVal);
      expect(wrapper.find('.amount-page__amount-box__amount__value').text()).toBe(val.expectedInputDivVal);
      input.simulate('change', { currentTarget: { value: '' } });
    });
  });

  it('should change page CTA based on paymentPageAvailable value', () => {
    expect(wrapper.find(ActionButton).exists()).toBeTruthy();
    expect(wrapper.find(PayWithBitpay).exists()).toBeFalsy();
    wrapper.setProps({ email: '[email protected]' });
    expect(wrapper.find(ActionButton).exists()).toBeFalsy();
    expect(wrapper.find(PayWithBitpay).exists()).toBeTruthy();
  });

  it('should have displayName value as title', () => {
    expect(wrapper.find('.amount-page__merchant-name').text()).toBe(CardConfigData.displayName);
  });

  it('should hide/show DiscountText based on discount value', () => {
    expect(wrapper.find(DiscountText).exists()).toBeFalsy();

    const cardConfigData: CardConfig = CardConfigData;
    const discounts: GiftCardDiscount = {
      code: 'discountCode',
      type: 'percentage',
      amount: 10
    };
    cardConfigData.discounts = [discounts];
    location = createLocation(path, { cardConfig: cardConfigData, merchant: MerchantData });
    wrapper = shallow(
      <Amount
        clientId={AmountProps.clientId}
        email={AmountProps.email}
        purchasedGiftCards={AmountProps.purchasedGiftCards}
        setPurchasedGiftCards={AmountProps.setPurchasedGiftCards}
        history={history}
        location={location}
        match={matchObj}
      />
    );
    expect(wrapper.find(DiscountText).exists()).toBeTruthy();
  });
});
Example #6
Source File: App.tsx    From clearflask with Apache License 2.0 4 votes vote down vote up
render() {
    const confStatus = this.server.getStore().getState().conf.status;
    if (!confStatus || confStatus === Status.PENDING) {
      return (<Loading />);
    } else if (confStatus === Status.REJECTED) {
      if (detectEnv() === Environment.PRODUCTION_SELF_HOST) {
        return (
          <RedirectIso to='/dashboard' />
        );
      }
      return (
        <ErrorPage msg={this.server.getStore().getState().conf.rejectionMessage || 'Failed to load'} />
      );
    }

    const projectId = this.server.getProjectId();
    const appRootId = `appRoot-${projectId}-${this.uniqId}`;

    return (
      <Provider store={this.server.getStore()}>
        {!this.props.isInsideContainer && (<SetAppFavicon />)}
        <SentryIdentifyUser />
        <IframeBroadcastPathname />
        <AppThemeProvider
          appRootId={appRootId}
          seed={projectId}
          isInsideContainer={this.props.isInsideContainer}
          supressCssBaseline={this.props.supressCssBaseline}
          containerStyle={theme => ({
            flexGrow: 1,
            display: 'flex',
            flexDirection: 'column',
            overflowY: this.props.settings?.demoScrollY ? 'scroll' : undefined,
          })}
        >
          <CookieConsenter />
          <PushNotificationListener server={this.server} />
          <ServerErrorNotifier />
          <CaptchaChallenger />
          <div
            key={appRootId}
            id={appRootId}
            style={{
              flexGrow: 1,
              display: 'flex',
              flexDirection: 'column',
              height: '100%',
              width: '100%',
              ...(this.props.isInsideContainer ? {
                position: 'relative',
              } : {}),
            }}
          >
            <PrivateProjectLogin server={this.server} slug={this.props.slug}>
              <MyLoadingBar />
              <CustomerExternalTrackers />
              <IntercomWrapperCustomer />
              <Route key='header' path='/:page?' render={props => (
                this.props.settings?.forceEmbed
                || ['embed', 'sso', 'oauth'].includes(props.match.params['page']))
                ? null
                : (
                  <Header
                    pageSlug={props.match.params['page'] || ''}
                    server={this.server}
                    pageChanged={this.pageChanged.bind(this)}
                  />
                )} />
              <AnimatedPageSwitch
                key='app-switch'
                render={(pageSlug: string) => (
                  <Route exact key={pageSlug} path={`/:embed(embed)?/${pageSlug}`} render={props => (
                    <BasePage
                      showFooter={!this.props.settings?.forceEmbed && !props.match.params['embed']}
                      customPageSlug={pageSlug}
                      isFrontPage={!this.props.settings?.forceEmbed && !props.match.params['embed'] && !pageSlug}
                    >
                      <AppDynamicPage
                        pageSlug={pageSlug}
                        server={this.server}
                      />
                    </BasePage>
                  )} />
                )}
                notFoundRoute={(
                  <RouteWithStatus httpCode={404} >
                    <BasePage
                      pageTitle='Page not found'
                      showFooter
                    >
                      <ErrorPage pageNotFound />
                    </BasePage>
                  </RouteWithStatus>
                )}
              >
                <Route key='user' path='/:embed(embed)?/user/:userId?' render={props => (
                  <BasePage suppressPageTitle showFooter={!this.props.settings?.forceEmbed && !props.match.params['embed']}>
                    <UserPage server={this.server} userId={props.match.params.userId} />
                  </BasePage>
                )} />
                <Route key='account' path='/:embed(embed)?/account' render={props => (
                  <BasePage pageTitle='Account' showFooter={!this.props.settings?.forceEmbed && !props.match.params['embed']}>
                    <AccountPage server={this.server} />
                  </BasePage>
                )} />
                <Route key='sso-oauth' path='/:type(sso|oauth)' render={props => (
                  <BasePage
                    pageTitle={props.match.params['type'] === 'sso' ? 'Single Sign-On' : 'OAuth'}
                    showFooter={!this.props.settings?.forceEmbed && !props.match.params['embed']}>
                    <SsoSuccessPage type={props.match.params['type']} />
                  </BasePage>
                )} />
                <Route key='post' path='/:embed(embed)?/post/:postId' render={props => (
                  <BasePage suppressPageTitle showFooter={!this.props.settings?.forceEmbed && !props.match.params['embed']}>
                    <PostPage
                      key={'postpage=' + props.match.params['postId']}
                      postId={props.match.params['postId'] || ''}
                      server={this.server}
                    />
                  </BasePage>
                )} />
              </AnimatedPageSwitch>
            </PrivateProjectLogin>
          </div>
        </AppThemeProvider>
      </Provider>
    );
  }