react-router-dom#useRouteMatch TypeScript Examples

The following examples show how to use react-router-dom#useRouteMatch. 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: Menu.tsx    From eth2stats-dashboard with MIT License 6 votes vote down vote up
Menu: React.FC<IMenuProps> = (props) => {
    let {url} = useRouteMatch();
    let {pathname} = useLocation();

    return (
        <ul className="flex items-center">
            <li className="mr-2 sm:mr-6 h-6 border-r border-grey-600 hidden sm:block"
                role="separator"/>
            <li className="mr-4 flex items-center">
                <Link to={`${url}`}>
                    <div className={`mr-4 flex items-center justify-center border p-2 w-10
                                    ${pathname === `${url}`
                        ? "border-blue-500 bg-blue-500 text-white"
                        : "text-grey-600 border-grey-600 hover:border-white hover:text-white transition"}`}>
                        <FontAwesomeIcon icon="list"/>
                    </div>
                </Link>
                <Link to={`${url}/map`}>
                    <div className={`flex items-center justify-center border p-2 w-10
                                    ${pathname === `${url}/map`
                        ? "border-blue-500 bg-blue-500 text-white"
                        : "text-grey-600 border-grey-600 hover:border-white hover:text-white transition"} `}>
                        <FontAwesomeIcon icon="map"/>
                    </div>
                </Link>
            </li>
        </ul>
    );
}
Example #2
Source File: SubmitProposal.tsx    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
SubmitProposalPage = observer(() => {
  let match = useRouteMatch();

  return (
    <Switch>
      <Route path={`${match.path}/custom`}>
        <NewProposalPage />{' '}
      </Route>
      <Route path={`${match.path}/contributor`}>
        <ContributorProposalPage />{' '}
      </Route>
    </Switch>
  );
})
Example #3
Source File: index.tsx    From metaflow-ui with Apache License 2.0 6 votes vote down vote up
RunContainer: React.FC = () => {
  const { t } = useTranslation();
  const { params } = useRouteMatch<RunPageParams>();

  const {
    data: run,
    status,
    error,
  } = useResource<IRun, IRun>({
    url: `/flows/${params.flowId}/runs/${params.runNumber}`,
    // Make sure that we subsribe to websocket with actual run_number. In some cases we dont have number in url but run id
    wsUrl: parseInt(params.runNumber)
      ? `/flows/${params.flowId}/runs/${params.runNumber}`
      : (result: IRun) => `/flows/${params.flowId}/runs/${result.run_number}`,
    subscribeToEvents: true,
    initialData: null,
  });

  return (
    <div>
      {status === 'Loading' && !run?.run_number && (
        <div style={{ textAlign: 'center', margin: '2rem 0' }}>
          <Spinner md />
        </div>
      )}

      {status === 'Error' && !run?.run_number && <APIErrorRenderer error={error} message={t('timeline.no-run-data')} />}

      {(status === 'Ok' || (status === 'Error' && error?.status === 404)) && run?.run_number && (
        <RunPage run={run} params={params} />
      )}
    </div>
  );
}
Example #4
Source File: TransactionNavTabs.tsx    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
export default function TransactionNavTabs() {
  const match = useRouteMatch();

  // Route Lookup for tabs
  const navUrls: any = {
    "/": 0,
    "/public": 0,
    "/contacts": 1,
    "/personal": 2,
  };

  // Set selected tab based on url
  const [value, setValue] = React.useState(navUrls[match.url]);

  const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
    setValue(newValue);
  };

  return (
    <Tabs
      value={value}
      onChange={handleChange}
      indicatorColor="secondary"
      centered
      data-test="nav-transaction-tabs"
    >
      <Tab label="Everyone" component={Link} to="/" data-test="nav-public-tab" />
      <Tab label="Friends" component={Link} to="/contacts" data-test="nav-contacts-tab" />
      <Tab label="Mine" component={Link} to="/personal" data-test="nav-personal-tab" />
    </Tabs>
  );
}
Example #5
Source File: AccountDetail.tsx    From abrechnung with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function AccountDetail({ group }) {
    const match = useRouteMatch();
    const accountID = parseInt(match.params.id);

    const account = useRecoilValue(groupAccountByID({ groupID: group.id, accountID: accountID }));

    useTitle(`${group.name} - Account ${account?.name}`);

    if (account === undefined) {
        return <Redirect to="/404" />;
    }

    return (
        <Grid container spacing={2}>
            {account.type === "personal" && (
                <Grid item xs={12}>
                    <MobilePaper>
                        <Typography variant="h6">Balance of {account.name}</Typography>
                        <BalanceHistoryGraph group={group} accountID={accountID} />
                    </MobilePaper>
                </Grid>
            )}
            {account.type === "clearing" && (
                <Grid item xs={12}>
                    <MobilePaper>
                        <Typography variant="h6">Clearing distribution of {account.name}</Typography>
                        <ClearingAccountDetail group={group} account={account} />
                    </MobilePaper>
                </Grid>
            )}
            <Grid item xs={12}>
                <MobilePaper>
                    <Typography variant="h6">Transactions involving {account.name}</Typography>
                    <AccountTransactionList group={group} accountID={accountID} />
                </MobilePaper>
            </Grid>
        </Grid>
    );
}
Example #6
Source File: CommandPalette.tsx    From amplication with Apache License 2.0 6 votes vote down vote up
CommandPalette = ({ trigger }: Props) => {
  const match = useRouteMatch<{ applicationId: string }>("/:applicationId/");

  const { applicationId } = match?.params || {};

  const history = useHistory();
  const [query, setQuery] = useState("");
  const handleChange = (inputValue: string, userQuery: string) => {
    setQuery(userQuery);
  };
  const { data } = useQuery<TData>(SEARCH, {
    variables: { query },
  });
  const commands = useMemo(
    () => (data ? getCommands(data, history, applicationId) : []),
    [data, history, applicationId]
  );

  return (
    <ReactCommandPalette
      trigger={trigger}
      commands={commands}
      onChange={handleChange}
      closeOnSelect
      showSpinnerOnSelect={false}
      theme={THEME}
      hotKeys={HOT_KEYS}
      options={{
        key: "name",
        keys: ["name", "appName"],
        allowTypo: true,
        scoreFn: calcCommandScore,
      }}
      renderCommand={CommandPaletteItem}
    />
  );
}
Example #7
Source File: FarmsContainer.tsx    From PolkaBridge-Farming with MIT License 6 votes vote down vote up
FarmsContainer: React.FC = () => {
  const { path } = useRouteMatch()
  // const { account } = useWallet()
  // const [onPresentWalletProviderModal] = useModal(<WalletProviderModal />)

  return <>
    <Route exact path={path}>
      <PageHeader
        icon={<img src={Logo} height="120" />}
        subtitle="Earn PBR tokens by staking PolkaBridge SPL Tokens."
        title="Select Your Favorite Pool"
      />
      <FarmCards />
    </Route>
    <Route path={`${path}/:farmId`}>
      <Farm />
    </Route>
  </>
}
Example #8
Source File: LaunchpadsContainer.tsx    From polkabridge-launchpad with MIT License 6 votes vote down vote up
LaunchpadsContainer: React.FC = () => {
  const { path } = useRouteMatch()
  // const { account } = useWallet()
  // const [onPresentWalletProviderModal] = useModal(<WalletProviderModal />)

  return <>
    <Route exact path={path}>
      <PageHeader
        icon={<img src={Logo} height="120" />}
        subtitle="Join hot IDO projects on PolkaBridge."
        title="Select Your Favorite Pool"
      />
      <LaunchpadCards />
    </Route>
    <Route path={`${path}/view/:launchpadId/:poolId`}>
      <Launchpad />
    </Route>
    <Route path={`${path}/join/:launchpadId/:poolId`}>
      <JoinLaunchpad />
    </Route>
  </>
}
Example #9
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 #10
Source File: LobbiesUtils.tsx    From client with GNU General Public License v3.0 6 votes vote down vote up
export function LinkButton({
  to,
  shortcut,
  children,
}: React.PropsWithChildren<{ to: string; shortcut?: string }>) {
  const { url } = useRouteMatch();
  const history = useHistory();

  function navigate() {
    history.push(`${url}${to}`);
  }

  // Adding className="button" so ButtonRow will add the flex stuff
  return (
    <ShortcutBtn
      className='button'
      size='stretch'
      onClick={navigate}
      onShortcutPressed={navigate}
      shortcutKey={shortcut}
      shortcutText={shortcut}
    >
      {children}
    </ShortcutBtn>
  );
}
Example #11
Source File: rasa.tsx    From covid-19 with MIT License 6 votes vote down vote up
RasaRoute: React.FC = () => {
  let { path } = useRouteMatch()

  return (
    <Switch>
      <Route exact path={path}>
        <Rasa />
      </Route>
      <Route exact path={`${path}/ci/:rid`}>
        <RasaCheckin />
      </Route>
      <Route exact path={`${path}/_test-navigation`}>
        <RasaTestNavigation />
      </Route>
      <Redirect to={path} />
    </Switch>
  )
}
Example #12
Source File: NodeLink.tsx    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a href that replaces the `/:path*` part of the current `<Route>`
 *
 * e.g. `/database/sample/data/a/b/c` -> `/database/sample/data/x/y/z`
 */
function useHrefWithinSameRoute(absolutePath: string) {
  const match = useRouteMatch();

  // remove the wildcard :path param, so we can append it manually
  const withoutPath = match.path.replace('/:path*', '');

  const result = matchPath(match.url, { path: withoutPath, strict: true });
  const baseUrl = result?.url || '';
  return baseUrl === '/' ? absolutePath : `${baseUrl}${absolutePath}`;
}
Example #13
Source File: PoolTabButtons.tsx    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
PoolTabButtons = ({ stakedOnly, setStakedOnly, hasStakeInFinishedPools, viewMode, setViewMode }) => {
  const { url, isExact } = useRouteMatch()
  const { t } = useTranslation()

  // const viewModeToggle = <ToggleView viewMode={viewMode} onToggle={(mode: ViewMode) => setViewMode(mode)} />

  const liveOrFinishedSwitch = (
    <Wrapper>
      <ButtonMenu activeIndex={isExact ? 0 : 1} scale="sm" variant="subtle">
        <ButtonMenuItem as={Link} to={`${url}`}>
          {t('Live')}
        </ButtonMenuItem>
        <NotificationDot show={hasStakeInFinishedPools}>
          <ButtonMenuItem as={Link} to={`${url}/history`}>
            {t('Finished')}
          </ButtonMenuItem>
        </NotificationDot>
      </ButtonMenu>
    </Wrapper>
  )

  const stakedOnlySwitch = (
    <ToggleWrapper>
      <Toggle checked={stakedOnly} onChange={() => setStakedOnly(!stakedOnly)} scale="sm" />
      <Text> {t('Staked only')}</Text>
    </ToggleWrapper>
  )

  return (
    <ViewControls>
      {/* {viewModeToggle} */}
      {stakedOnlySwitch}
      {liveOrFinishedSwitch}
    </ViewControls>
  )
}
Example #14
Source File: index.tsx    From interbtc-ui with Apache License 2.0 6 votes vote down vote up
Dashboard = (): JSX.Element => {
  const match = useRouteMatch();

  return (
    <MainContainer className='fade-in-animation'>
      <Switch>
        <Route path={PAGES.DASHBOARD_VAULTS}>
          <Vaults />
        </Route>
        <Route path={PAGES.DASHBOARD_PARACHAIN}>
          <Parachain />
        </Route>
        <Route path={PAGES.DASHBOARD_ORACLES}>
          <Oracles />
        </Route>
        <Route path={PAGES.DASHBOARD_ISSUE_REQUESTS}>
          <IssueRequests />
        </Route>
        <Route path={PAGES.DASHBOARD_REDEEM_REQUESTS}>
          <RedeemRequests />
        </Route>
        <Route path={PAGES.DASHBOARD_RELAY}>
          <BTCRelay />
        </Route>
        <Route path={match.path}>
          <Home />
        </Route>
      </Switch>
    </MainContainer>
  );
}
Example #15
Source File: HubView.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
HubView = () => {
  const { path } = useRouteMatch()
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(fetchHubImages())
  }, [dispatch])

  return (
    <div className="px-4">
      <Switch>
        <Route exact path={path}>
          <HubOverviewActionsContainer />
          <HubRecommendedCategories />
          <HubImagesListPreview />
        </Route>
        <Route path={`${path}/explore`}>
          <HubImagesList />
        </Route>
      </Switch>
    </div>
  )
}
Example #16
Source File: useJobsReducer.ts    From jobsgowhere with MIT License 6 votes vote down vote up
export default function usePostsReducer(): [JobsState, JobsActions] {
  const [state, dispatch] = React.useReducer(JobsReducer, initialState);

  const setActiveJob = React.useCallback((id?: string): void => {
    dispatch({ type: SET_ACTIVE_JOB, payload: id });
  }, []);
  const toggleFavouriteJob = React.useCallback((job: PostInterface): void => {
    dispatch({ type: TOGGLE_FAVOURITE_JOB, payload: job });
  }, []);
  const refreshJobs = React.useCallback((jobs: PostInterface[]): void => {
    dispatch({ type: REFRESH_JOBS, payload: jobs });
  }, []);
  const updateJobs = React.useCallback((jobs: PostInterface[]): void => {
    dispatch({ type: UPDATE_JOBS, payload: jobs });
  }, []);
  const actions: JobsActions = React.useMemo(() => {
    return {
      setActiveJob,
      toggleFavouriteJob,
      refreshJobs,
      updateJobs,
    };
  }, [setActiveJob, toggleFavouriteJob, refreshJobs, updateJobs]);

  const match = useRouteMatch<{ id: string }>("/jobs/:id");
  const id = match?.params?.id;

  React.useEffect(() => {
    if (!state.fetched || state.jobs.length === 0) return;

    if (id && state.activeJob?.id !== id) {
      setActiveJob(id);
    } else if (!state.activeJob) {
      setActiveJob(state.jobs[0].id);
    }
  }, [id, setActiveJob, state]);

  return [state, actions];
}
Example #17
Source File: useRouter.ts    From django-react-typescript with MIT License 6 votes vote down vote up
export function useRouter() {
  const params = useParams();
  const location = useLocation();
  const history = useHistory();
  const match = useRouteMatch();

  // Return our custom router object
  // Memoize so that a new object is only returned if something changes
  return useMemo(() => {
    return {
      // For convenience add push(), replace(), pathname at top level
      push: history.push,
      replace: history.replace,
      pathname: location.pathname,
      // Merge params and parsed query string into single "query" object
      // so that they can be used interchangeably.
      // Example: /:topic?sort=popular -> { topic: "react", sort: "popular" }
      query: {
        ...queryString.parse(location.search), // Convert string to object
        ...params,
      },
      // Include match, location, history objects so we have
      // access to extra React Router functionality if needed.
      match,
      location,
      history,
    };
  }, [params, match, location, history]);
}
Example #18
Source File: TeamLink.tsx    From js-ts-monorepos with BSD 2-Clause "Simplified" License 6 votes vote down vote up
TeamLink: React.FunctionComponent<{ team: ITeam }> = ({ team }) => {
  const match = useRouteMatch({
    path: `/team/${team.id}`,
    exact: false,
  });

  return (
    <Link
      to={`/team/${team.id}/channel/${team.channels[0].id}`}
      className={
        "team-selector__team-button cursor-pointer rounded-lg p-2 pl-4 inline-block sm:block no-underline opacity-25 " +
        (match ? "opacity-100" : "")
      }
    >
      <div className="bg-white h-12 w-12 flex items-center justify-center text-black text-2xl font-semibold rounded-lg mb-1 overflow-hidden">
        <img
          className="team-selector__team-logo"
          src={team.iconUrl}
          alt={`Join the ${team.name} chat`}
        />
      </div>
    </Link>
  );
}
Example #19
Source File: Dropdown.tsx    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
NavigationOption: FC<{ title: string; path: string; onClick: () => void }> = ({ title, path, onClick }) => {
  const routeMatch = useRouteMatch(path)

  return (
    <NavLink to={path}>
      <Option isDropdown={false} onClick={onClick} selected={routeMatch?.isExact} optionName={title}>
        {title}
      </Option>
    </NavLink>
  )
}
Example #20
Source File: index.tsx    From oasis-wallet-web with Apache License 2.0 6 votes vote down vote up
export function TransitionRoute(props: Props) {
  const fullPath = props.path
  const Component = props.component as any
  const nodeRef = useRef(null)
  let match = useRouteMatch(fullPath)

  return (
    <Route exact={props.exact} path={fullPath} key={props.path}>
      <CSSTransition
        in={match != null}
        timeout={300}
        classNames="fade"
        key={props.path}
        nodeRef={nodeRef}
        unmountOnExit
      >
        <Transition ref={nodeRef}>
          <Component />
        </Transition>
      </CSSTransition>
    </Route>
  )
}
Example #21
Source File: columns.tsx    From payload with MIT License 6 votes vote down vote up
CreatedAtCell: React.FC<CreatedAtCellProps> = ({ collection, global, id, date }) => {
  const { routes: { admin }, admin: { dateFormat } } = useConfig();
  const { params: { id: docID } } = useRouteMatch<{ id: string }>();

  let to: string;

  if (collection) to = `${admin}/collections/${collection.slug}/${docID}/versions/${id}`;
  if (global) to = `${admin}/globals/${global.slug}/versions/${id}`;

  return (
    <Link to={to}>
      {date && format(new Date(date), dateFormat)}
    </Link>
  );
}
Example #22
Source File: index.tsx    From frontend-ui with GNU General Public License v3.0 6 votes vote down vote up
FarmTabButtons = () => {
  const { url, isExact } = useRouteMatch()
  const TranslateString = useI18n()

  return (
    <Wrapper>
      <ButtonMenu activeIndex={!isExact ? 1 : 0} size="sm" variant="subtle">
        <ButtonMenuItem as={Link} to={`${url}`}>
          {TranslateString(999, 'Active')}
        </ButtonMenuItem>
        <ButtonMenuItem as={Link} to={`${url}/history`}>
          {TranslateString(999, 'Inactive')}
        </ButtonMenuItem>
      </ButtonMenu>
    </Wrapper>
  )
}
Example #23
Source File: index.tsx    From datart with Apache License 2.0 6 votes vote down vote up
export function MemberPage() {
  const { params } = useRouteMatch<MemberPageRouteParams>();
  useMemberSlice();

  return (
    <Container>
      <Sidebar />
      <Switch>
        <Route
          path="/organizations/:orgId/members/:memberId"
          component={MemberDetailPage}
        />
        <Route
          path="/organizations/:orgId/roles/:roleId"
          component={RoleDetailPage}
        />
      </Switch>
    </Container>
  );
}
Example #24
Source File: index.tsx    From endbot with MIT License 6 votes vote down vote up
export function Apps() {
	const { path } = useRouteMatch();

	return (
		<Switch>
			<Route exact path={path} component={TicketList}/>
			<Route exact path={`${path}/:app_id`} component={Channel}/>
		</Switch>
	)
}
Example #25
Source File: index.tsx    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
FarmTabButtons: React.FC<FarmTabButtonsProps> = ({ hasStakeInFinishedFarms }) => {
  const { url } = useRouteMatch()
  const location = useLocation()
  const { t } = useTranslation()

  let activeIndex
  switch (location.pathname) {
    case '/farms':
      activeIndex = 0
      break
    case '/farms/history':
      activeIndex = 1
      break
    case '/farms/archived':
      activeIndex = 2
      break
    default:
      activeIndex = 0
      break
  }

  return (
    <Wrapper>
      <ButtonMenu activeIndex={activeIndex} scale="sm">
        <ButtonMenuItem as={Link} to={`${url}`}>
          {t('Live')}
        </ButtonMenuItem>
        <NotificationDot show={hasStakeInFinishedFarms}>
          <ButtonMenuItem id="finished-farms-button" as={Link} to={`${url}/history`}>
            {t('Finished')}
          </ButtonMenuItem>
        </NotificationDot>
      </ButtonMenu>
    </Wrapper>
  )
}
Example #26
Source File: SigninSignupPage.tsx    From firebase-react-typescript-project-template with MIT License 5 votes vote down vote up
SigninSignupPage = ({ variant }: SigninSignupPageProps) => {
  const classes = useStyles();

  const isSm = useMediaQuery((theme: Theme) => theme.breakpoints.down("sm"));

  const location = useLocation();
  const from = (location?.state as any)?.from?.pathname || APP_LANDING;

  const resetPasswordMatch = useRouteMatch({
    path: RESET_PASSWORD_PATH,
  });

  const { user } = useSession();
  // if user authed, redirect to home dashboard
  if (user?.emailVerified) {
    return <Redirect to={from} />;
  }

  let component = null;
  let Img = LoginImg;

  if (resetPasswordMatch) {
    component = <ResetPassword />;
    Img = ForgotPasswordImg;
  } else if (user) {
    component = <EmailVerification />;
    Img = NewEmailImg;
  } else {
    component = <SigninSignupForm variant={variant} from={from} />;
    Img = variant === "signin" ? LoginImg : NewAccountImg;
  }

  return (
    <AuthContainer>
      <Grid container>
        <Grid item xs={12} md={6} lg={5} className={classes.contentContainer}>
          <Logo className={classes.logo} />
          {component}
        </Grid>
        {!isSm && (
          <Grid item md={6} lg={7} className={classes.imgContainer}>
            <Img className={classes.img} />
          </Grid>
        )}
      </Grid>
    </AuthContainer>
  );
}
Example #27
Source File: BankAccountsContainer.tsx    From End-to-End-Web-Testing-with-Cypress with MIT License 5 votes vote down vote up
BankAccountsContainer: React.FC<Props> = ({ authService, bankAccountsService }) => {
  const match = useRouteMatch();
  const classes = useStyles();
  const [authState] = useService(authService);
  const [bankAccountsState, sendBankAccounts] = useService(bankAccountsService);

  const currentUser = authState?.context.user;

  const createBankAccount = (payload: any) => {
    sendBankAccounts("CREATE", payload);
  };

  const deleteBankAccount = (payload: any) => {
    sendBankAccounts("DELETE", payload);
  };

  useEffect(() => {
    sendBankAccounts("FETCH");
  }, [sendBankAccounts]);

  if (match.url === "/bankaccounts/new" && currentUser?.id) {
    return (
      <Paper className={classes.paper}>
        <Typography component="h2" variant="h6" color="primary" gutterBottom>
          Create Bank Account
        </Typography>
        <BankAccountForm userId={currentUser?.id} createBankAccount={createBankAccount} />
      </Paper>
    );
  }

  return (
    <Paper className={classes.paper}>
      <Grid container direction="row" justify="space-between" alignItems="center">
        <Grid item>
          <Typography component="h2" variant="h6" color="primary" gutterBottom>
            Bank Accounts
          </Typography>
        </Grid>
        <Grid item>
          <Button
            variant="contained"
            color="primary"
            size="large"
            component={RouterLink}
            to="/bankaccounts/new"
            data-test="bankaccount-new"
          >
            Create
          </Button>
        </Grid>
      </Grid>
      <BankAccountList
        bankAccounts={bankAccountsState?.context.results!}
        deleteBankAccount={deleteBankAccount}
      />
    </Paper>
  );
}
Example #28
Source File: Group.tsx    From abrechnung with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function Group() {
    const match = useRouteMatch();
    const groupID = match.params["id"];
    const group = useRecoilValue(groupById(parseInt(groupID)));

    if (group === undefined) {
        return <Redirect to="/404" />;
    }

    // TODO: handle 404
    return (
        <Layout group={group}>
            <Switch>
                <Route exact path={`${match.path}/log`}>
                    <GroupLog group={group} />
                </Route>
                <Route exact path={`${match.path}/accounts`}>
                    <Suspense fallback={<Loading />}>
                        <AccountList group={group} />
                    </Suspense>
                </Route>
                <Route exact path={`${match.path}/members`}>
                    <Suspense fallback={<Loading />}>
                        <GroupMemberList group={group} />
                    </Suspense>
                </Route>
                <Route exact path={`${match.path}/detail`}>
                    <Suspense fallback={<Loading />}>
                        <GroupSettings group={group} />
                    </Suspense>
                </Route>
                <Route exact path={`${match.path}/invites`}>
                    <Suspense fallback={<Loading />}>
                        <GroupInvites group={group} />
                    </Suspense>
                </Route>
                <Route exact path={`${match.path}/balances`}>
                    <Suspense fallback={<Loading />}>
                        <Balances group={group} />
                    </Suspense>
                </Route>
                <Route exact path={`${match.path}/`}>
                    <Suspense fallback={<Loading />}>
                        <TransactionList group={group} />
                    </Suspense>
                </Route>
                <Route path={`${match.path}/transactions/:id([0-9]+)`}>
                    <Suspense fallback={<Loading />}>
                        <Transaction group={group} />
                    </Suspense>
                </Route>
                <Route path={`${match.path}/accounts/:id([0-9]+)`}>
                    <Suspense fallback={<Loading />}>
                        <AccountDetail group={group} />
                    </Suspense>
                </Route>
            </Switch>
        </Layout>
    );
}
Example #29
Source File: index.tsx    From react-app-architecture with Apache License 2.0 5 votes vote down vote up
function App(): ReactElement {
  const willMount = useRef(true);
  const classes = useStyles();
  const dispatch = useDispatch();
  const match = useRouteMatch();
  const [cookies, setCookie, removeCookie] = useCookies([KEY_AUTH_DATA]);
  const { currentPageTitle } = useStateSelector(({ appState }) => appState);
  const { data: authData, isLoggedIn } = useStateSelector(({ authState }) => authState);

  // only run on the client
  if (typeof window !== 'undefined' && willMount.current) {
    const authData = cookies[KEY_AUTH_DATA];
    if (authData) dispatch(updateAuthData.action(authData));
    willMount.current = false;
  }

  useEffect(() => {
    removeAppLoader();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (currentPageTitle) setPageTitle(currentPageTitle);
  }, [currentPageTitle]);

  useEffect(() => {
    scrollPageToTop();
  }, [match]);

  useEffect(() => {
    if (isLoggedIn) {
      setAuthCookies();
    } else {
      removeAuthCookies();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isLoggedIn]);

  const setAuthCookies = () => {
    if (authData?.tokens?.accessToken) {
      const expiryInSec = 30 * 24 * 60 * 60; // 30 days
      setCookie(KEY_AUTH_DATA, authData, {
        path: '/',
        maxAge: expiryInSec,
        sameSite: 'strict',
        secure: process.env.NODE_ENV === 'production', // only https access allowed
      });
    }
  };

  const removeAuthCookies = () => {
    removeCookie(KEY_AUTH_DATA, { path: '/' });
  };

  return (
    <Fragment>
      <CssBaseline />
      <div className={classes.root}>
        <Header />
        <div className={classes.content}>
          <Routes />
        </div>
        <Footer />
      </div>
    </Fragment>
  );
}