react-router-dom#useParams TypeScript Examples

The following examples show how to use react-router-dom#useParams. 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: index.tsx    From Demae with MIT License 6 votes vote down vote up
Content = () => {
	const { orderID } = useParams<{ orderID?: string }>()
	const theme = useTheme();
	const matches = useMediaQuery(theme.breakpoints.down("sm"));

	if (matches) {
		if (orderID) {
			return (
				<NavigationView>
					<ContentView>
						<Detail orderID={orderID} />
					</ContentView>
				</NavigationView>
			)
		}

		return (
			<NavigationView>
				<ListView height="100%">
					<List />
				</ListView>
			</NavigationView>
		)
	}

	return (
		<NavigationView>
			<ListView height="100%">
				<List />
			</ListView>
			<Divider orientation="vertical" flexItem />
			<ContentView>
				<Detail orderID={orderID} />
			</ContentView>
		</NavigationView>
	)
}
Example #2
Source File: Experiment.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
export default function Experiment(): JSX.Element | null {
  const { experimentIdSlug, view: viewRaw = ExperimentView.Overview } =
    useParams<{
      experimentIdSlug: string
      view: string
    }>()
  const experimentId = parseIdSlug(experimentIdSlug)
  const view = yup.string().defined().oneOf(Object.values(ExperimentView)).validateSync(viewRaw)
  const debugMode = isDebugMode()

  debug(`ExperimentPage#render experimentId:%o view:%o debugMode:%o`, experimentId, view, debugMode)

  return <ExperimentPageView {...{ experimentId, debugMode, view }} />
}
Example #3
Source File: LoginLoader.tsx    From caritas-onlineBeratung-frontend with GNU Affero General Public License v3.0 6 votes vote down vote up
LoginLoader = ({
	handleUnmatch,
	legalComponent,
	stageComponent
}: LoginLoaderProps) => {
	const [isValidResort, setIsValidResort] = useState<boolean>();
	const { consultingTypeSlug } = useParams();

	useEffect(() => {
		if (!consultingTypeSlug) {
			setIsValidResort(true);
			return;
		}

		if (!isValidConsultingTypeSlug(consultingTypeSlug)) {
			handleUnmatch();
			return;
		}

		apiGetConsultingType({ consultingTypeSlug }).then((result) => {
			if (result) setIsValidResort(true);
			else handleUnmatch();
		});
	}, [consultingTypeSlug, handleUnmatch]);

	if (isValidResort) {
		return (
			<Login
				legalComponent={legalComponent}
				stageComponent={stageComponent}
			/>
		);
	} else {
		return null;
	}
}
Example #4
Source File: SidebarInfoCard.tsx    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
SidebarInfoCard = () => {
  const { guild_id: guildId } =
    useParams<{ chain_name?: string; guild_id?: string }>();
  const { data } = useGuildConfig(guildId);

  const quorum = useVotingPowerPercent(
    data?.votingPowerForProposalExecution,
    data?.totalLocked
  );

  return (
    <SidebarCard header={<SidebarCardHeader>Information</SidebarCardHeader>}>
      <SidebarCardContent>
        <Row>
          <Label>Consensus System</Label>
          <ColoredLabel>Guild</ColoredLabel>
        </Row>
        <Row>
          <Label>Proposal Duration</Label>
          <ColoredLabel>
            {data?.proposalTime ? (
              duration(data?.proposalTime?.toNumber(), 'seconds').humanize()
            ) : (
              <Skeleton width={50} />
            )}
          </ColoredLabel>
        </Row>
        <Row>
          <Label>Quorum</Label>
          <ColoredLabel>
            {quorum != null ? `${quorum}%` : <Skeleton width={50} />}
          </ColoredLabel>
        </Row>
      </SidebarCardContent>
    </SidebarCard>
  );
}
Example #5
Source File: NativeListItem.tsx    From GTAV-NativeDB with MIT License 6 votes vote down vote up
function NativeListItem({ nativeHash }: NativeListItemProps) {
  const native = useNative(nativeHash)
  const history = useHistory()
  const { native: selectedNativeHash } = useParams<{ native: string } >()
  
  const onClick = useCallback(() => {
    history.push(`/natives/${nativeHash}${history.location.search}`)
  }, [history, nativeHash])

  return (
    <ListItem
      onClick={onClick}
      selected={selectedNativeHash === nativeHash}
      button
      dense
    >
      <NativeDefinition
        name={native.name}
        returnType={native.returnType}
        params={native.params}
        nameCopyable={false}
        noWrap
      />
    </ListItem>
  )
}
Example #6
Source File: ArticlePage.tsx    From personal-archive with MIT License 6 votes vote down vote up
ArticlePage: FC = () => {
  const {id} = useParams() as any
  const [fetching, getArticle, article, error] = useRequestGetArticle()
  const history = useHistory()

  useEffect(() => {
    getArticle(id)
  }, [id, getArticle])

  useEffect(() => {
    if (error && error.response?.status === 404) {
      setTimeout(() => history.push('/'), 1000)
    }
  }, [error, history])

  const onReload = () => getArticle(id)

  return (
    <ArticleTagTreeLayout
      loading={fetching}
      title={article ? article.title : undefined}
    >
      {
        article && (
          <>
            <ArticleTitle article={article} onReload={onReload}/>
            <ArticleTags article={article} onReload={onReload}/>
            <ArticleLink article={article}/>
            <ArticleContent article={article}/>
            <CommandPalette article={article} onReload={onReload}/>
          </>
        )
      }
    </ArticleTagTreeLayout>
  )
}
Example #7
Source File: index.tsx    From gonear-name with The Unlicense 6 votes vote down vote up
Bid = () => {
  useTopScroll()
  const { bidId } = useParams<{ bidId: string }>();
  const { near }: { near: INearProps | null } = useContext(NearContext)
  const [bidSafety, setBidSafety] = useState<IBidSafety>()
  const [profile, setProfile] = useState<IProfile | null>(null)
  const toMarket = useToMarket()

  const { data: bidInfo } = useSWR(
    ['get_bid', near?.connected, bidId], 
    () => near?.api.get_bid(bidId),
    { refreshInterval: 60000 }
  )
  
  const getBidSafety = async () => {
    if (!near) return
    const bs = await near.api.get_bid_safety(bidId)
    if (bs) setBidSafety(bs)
  }

  const getProfile = async () => {
    if (!near) return
    const pr = await near.api.get_profile(near.signedAccountId)
    if (pr) setProfile(pr);
  }

  useEffect(() => {
    getProfile()
    getBidSafety()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [near?.signedAccountId])

  return (
    <Container>
      <BackButton onClick={toMarket} />
      { near && bidInfo && bidSafety && <BidComponent bidInfo={bidInfo} bidSafety={bidSafety} near={near} profile={profile} /> }
    </Container>
  )
}
Example #8
Source File: detail.tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
DetailPage: React.FC = () => {
  const { id } = useParams();

  return (
    <>
      <h2>Hello from Detail page</h2>
      <h3>User Id: {id}</h3>
      <Link to="/list">Back to list page</Link>
    </>
  );
}
Example #9
Source File: TransactionDetailContainer.tsx    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
TransactionDetailsContainer: React.FC<Props> = ({ authService }) => {
  const { transactionId }: Params = useParams();
  const [authState] = useService(authService);
  const [transactionDetailState, sendTransactionDetail] = useMachine(transactionDetailMachine);
  useEffect(() => {
    sendTransactionDetail("FETCH", { transactionId });
  }, [sendTransactionDetail, transactionId]);

  const transactionLike = (transactionId: Transaction["id"]) =>
    sendTransactionDetail("CREATE", { entity: "LIKE", transactionId });

  const transactionComment = (payload: any) =>
    sendTransactionDetail("CREATE", { entity: "COMMENT", ...payload });

  const transactionUpdate = (payload: any) => sendTransactionDetail("UPDATE", payload);

  const transaction = first(transactionDetailState.context?.results);
  const currentUser = authState?.context?.user;

  return (
    <>
      {transactionDetailState.matches("idle") && (
        <div>
          Loading...
          <br />
        </div>
      )}
      {currentUser && transactionDetailState.matches("success") && (
        <TransactionDetail
          transaction={transaction}
          transactionLike={transactionLike}
          transactionComment={transactionComment}
          transactionUpdate={transactionUpdate}
          currentUser={currentUser}
        />
      )}
    </>
  );
}
Example #10
Source File: Main.tsx    From Full-Stack-React-TypeScript-and-Node with MIT License 6 votes vote down vote up
Main = () => {
  const { categoryId } = useParams();
  const [category, setCategory] = useState<Category | undefined>();
  const [threadCards, setThreadCards] = useState<Array<JSX.Element> | null>(
    null
  );

  useEffect(() => {
    console.log("main categoryId", categoryId);

    if (categoryId && categoryId > 0) {
      getThreadsByCategory(categoryId).then((threads) => {
        const cards = threads.map((th) => {
          return <ThreadCard key={`thread-${th.id}`} thread={th} />;
        });
        if (!category) {
          setCategory(threads[0].category);
        }
        setThreadCards(cards);
      });
    }
  }, [categoryId]);

  return (
    <main className="content">
      <MainHeader category={category} />
      <div>{threadCards}</div>
    </main>
  );
}
Example #11
Source File: Manga.tsx    From Tachidesk-WebUI with Mozilla Public License 2.0 6 votes vote down vote up
export default function Manga() {
    const { setTitle } = useContext(NavbarContext);
    useEffect(() => { setTitle('Manga'); }, []); // delegate setting topbar action to MangaDetails

    const { id } = useParams<{ id: string }>();

    const [manga, setManga] = useState<IManga>();

    useEffect(() => {
        if (manga === undefined || !manga.freshData) {
            client.get(`/api/v1/manga/${id}/?onlineFetch=${manga !== undefined}`)
                .then((response) => response.data)
                .then((data: IManga) => {
                    setManga(data);
                    setTitle(data.title);
                });
        }
    }, [manga]);

    return (
        <Box sx={{ display: { md: 'flex' }, overflow: 'hidden' }}>
            <LoadingPlaceholder
                shouldRender={manga !== undefined}
                component={MangaDetails}
                componentProps={{ manga }}
            />

            <ChapterList id={id} />
        </Box>
    );
}
Example #12
Source File: index.tsx    From pPhone2 with MIT License 6 votes vote down vote up
NotePage: React.FC<any> = () => {
    let { id } = useParams();
    let note = defaultNotes[Number(id)]
    if (!note) {
        // create last_id
        note = { id: 1, title: "New file", content: "Your note" }
    }

    return (
        <div className="note-write-container">
            <textarea className="note-write-input" value={note.content} />
        </div>        
    )
}
Example #13
Source File: booksmark.tsx    From kinopub.webos with MIT License 6 votes vote down vote up
BookmarkView: React.FC = () => {
  const { bookmarkId } = useParams<RouteParams>();
  const location = useLocation<{ title?: string }>();
  const queryResult = useApiInfinite('bookmarkItems', [bookmarkId!]);
  const { title = queryResult?.data?.pages?.[0]?.folder?.title } = location.state || {};

  return (
    <>
      <Seo title={`Закладка: ${title}`} />
      <ItemsListInfinite title={title} queryResult={queryResult} />
    </>
  );
}
Example #14
Source File: ProjectPage.tsx    From frontend with Apache License 2.0 6 votes vote down vote up
ProjectPage = () => {
  const classes = useStyles();
  const { projectId } = useParams<{ projectId: string }>();
  const navigate = useNavigate();
  const helpDispatch = useHelpDispatch();

  useEffect(() => {
    setHelpSteps(helpDispatch, PROJECT_PAGE_STEPS);
  });

  return (
    <React.Fragment>
      <Grid container className={classes.root}>
        <Grid item xs={3} className={classes.root}>
          <Box height="9%" id={LOCATOR_PROJECT_PAGE_SELECT_PROJECT}>
            <ProjectSelect
              projectId={projectId}
              onProjectSelect={(id) => navigate(buildProjectPageUrl(id))}
            />
          </Box>
          <Box height="91%" id={LOCATOR_PROJECT_PAGE_BUILD_LIST}>
            <BuildList />
          </Box>
        </Grid>
        <Grid item xs={9} className={classes.root}>
          <Box height="15%">
            <BuildDetails />
          </Box>
          <Box height="85%" id={LOCATOR_PROJECT_PAGE_TEST_RUN_LIST}>
            <TestRunList />
          </Box>
        </Grid>
      </Grid>
      <TestDetailsDialog />
    </React.Fragment>
  );
}
Example #15
Source File: ArtistStatsWrapper.tsx    From your_spotify with GNU General Public License v3.0 6 votes vote down vote up
export default function ArtistStatsWrapper() {
  const params = useParams();
  const stats = useAPI(api.getArtistStats, params.id || '');

  if (stats === null) {
    return (
      <FullscreenCentered>
        <CircularProgress />
        <div>
          <Text element="h3">Loading your stats</Text>
        </div>
      </FullscreenCentered>
    );
  }

  if ('code' in stats) {
    return (
      <FullscreenCentered>
        <Text element="h3">
          You never listened to this artist, might be someone else registered
        </Text>
      </FullscreenCentered>
    );
  }

  return <ArtistStats stats={stats} />;
}
Example #16
Source File: ArticlePage.tsx    From ts-redux-react-realworld-example-app with MIT License 6 votes vote down vote up
export function ArticlePage() {
  const { slug } = useParams<{ slug: string }>();

  const {
    articlePage: { article, commentSection, metaSection },
    app: { user },
  } = useStore(({ articlePage, app }) => ({
    articlePage,
    app,
  }));

  useEffect(() => {
    onLoad(slug);
  }, [slug]);

  return article.match({
    none: () => <div>Loading article...</div>,
    some: (article) => (
      <div className='article-page'>
        <ArticlePageBanner {...{ article, metaSection, user }} />

        <div className='container page'>
          <div className='row article-content'>
            <div className='col-md-12'>{article.body}</div>
            <TagList tagList={article.tagList} />
          </div>

          <hr />

          <div className='article-actions'>
            <ArticleMeta {...{ article, metaSection, user }} />
          </div>

          <CommentSection {...{ user, commentSection, article }} />
        </div>
      </div>
    ),
  });
}
Example #17
Source File: GithubApp.tsx    From argo-react with MIT License 6 votes vote down vote up
GithubSignup = () => {
  const params = useParams<{ id: string }>();

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

  const signInWithGithub = async () => {
    import("../../../../../../config").then((config: any) => {
      const githubAppInUrl = `${config.default.urls.API_URL}/auth/github/app/auth/${params.id}`;
      window.open(githubAppInUrl, "_self");
    });
  };

  return <Loading />;
}
Example #18
Source File: useRouteRefParams.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
 * React hook for retrieving dynamic params from the current URL.
 * @param _routeRef - Ref of the current route.
 * @public
 */
export function useRouteRefParams<Params extends AnyParams>(
  _routeRef: RouteRef<Params> | SubRouteRef<Params>,
): Params {
  return useParams() as Params;
}
Example #19
Source File: edit-detail.tsx    From frontend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
WikiEditPage: React.FC = () => {
  const { id } = useParams()
  return (
    <div>
      <span>维基编辑页: {id}</span>
      <DetailEditor />
    </div>
  )
}
Example #20
Source File: Domain.tsx    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
Domain: React.FC = () => {
  const { domainId } = useParams();

  return (
    <div className={classes.root}>
      <div className={classes.inner}>
        <DomainDetails domainId={domainId} />
      </div>
    </div>
  );
}
Example #21
Source File: SwaggerToolboxPage.tsx    From one-platform with MIT License 5 votes vote down vote up
SwaggerToolboxPage = (): JSX.Element => {
  const { envSlug } = useParams();
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const { isLoading, data: schemaData } = useGetApiSchemaFile({ envSlug });
  const [isDecodingFile, setIsDecodingFile] = useToggle();

  const schema = schemaData?.fetchAPISchema?.schema;
  const namespaceSlug = schemaData?.fetchAPISchema?.namespaceSlug;
  const file = schemaData?.fetchAPISchema?.file;

  useRegisterRecentVisit({
    isLoading: isLoading || isDecodingFile,
    log: useMemo(
      () => ({
        title: schema?.name || '',
        tool: 'swagger',
        url: pathname,
        id: namespaceSlug as string,
        envSlug: envSlug as string,
      }),
      [pathname, namespaceSlug, schema?.name, envSlug]
    ),
    onRemoveId: namespaceSlug,
  });

  const schemaFile = useMemo(() => {
    if (file) {
      try {
        setIsDecodingFile.on();
        const data = yaml.load(window.atob(file));
        return data as object;
      } catch (error) {
        window.OpNotification.danger({
          subject: 'Failed to parse file!!',
        });
      } finally {
        setIsDecodingFile.off();
      }
    }
    return '';
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [file]);

  if (isLoading || isDecodingFile) {
    return (
      <Bullseye>
        <Spinner size="xl" />
      </Bullseye>
    );
  }

  if (!file) {
    return (
      <Bullseye>
        <EmptyState>
          <EmptyStateIcon icon={CubeIcon} />
          <Title headingLevel="h4" size="lg">
            Sorry, Couldn&apos;t find this API
          </Title>
          <Button variant="primary" onClick={() => navigate('/apis')}>
            Go Back
          </Button>
        </EmptyState>
      </Bullseye>
    );
  }

  return <SwaggerUI spec={schemaFile} tryItOutEnabled />;
}
Example #22
Source File: List.tsx    From Demae with MIT License 5 votes vote down vote up
ListItem = ({ data }: { data: Order }) => {
	const classes = useStyles();
	const { orderID } = useParams<{ orderID?: string }>()
	const salesMethod = useSalesMethod()
	const orderedDate = Dayjs(data.createdAt.toDate())
	const currency = data.currency
	const amount = data.amount || 0
	const price = new Intl.NumberFormat("ja-JP", { style: "currency", currency: currency }).format(amount)
	const imageURL = data.imageURLs().length > 0 ? data.imageURLs()[0] : undefined

	return (
		<Link className={classes.list} to={`/admin/orders/${data.id}` + (salesMethod ? `?salesMethod=${salesMethod}` : "")}>
			<Box>
				<Box padding={1} paddingY={2} style={{
					backgroundColor: orderID === data.id ? "rgba(0, 0, 140, 0.03)" : "inherit"
				}}>
					<Grid container>
						<Grid item xs={1}>
						</Grid>
						<Grid item xs={2}>
							<Avatar variant="rounded" src={imageURL} >
								<ImageIcon />
							</Avatar>
						</Grid>
						<Grid item xs={9}>
							<Box display="flex" justifyContent="space-between">
								<Box>
									<Typography variant="subtitle1">{data.title}</Typography>
									<Typography variant="body2">{data.id}</Typography>
									<Typography variant="caption">
										{orderedDate.format("YYYY-MM-DD HH:mm:ss")}
									</Typography>
								</Box>
							</Box>
							<Box className={classes.tags}>
								<Chip size="small" label={DeliveryStatusLabel[data.deliveryStatus]} />
								<Chip size="small" label={SalesMethodLabel[data.salesMethod]} />
								<Chip size="small" label={PaymentStatusLabel[data.paymentStatus]} />
								{
									data.tags.map((tag, index) => {
										return <Chip key={index} size="small" label={tag} />
									})
								}
							</Box>
						</Grid>
					</Grid>
				</Box>
				<Divider />
			</Box>
		</Link>
	)
}
Example #23
Source File: wh.convert.to-basset.tsx    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
WormholeConvertToBAsset = () => {
  const { tokenSymbol } = useParams();

  const { data: bAssetInfo } = useBAssetInfoByTokenSymbolQuery(tokenSymbol);

  return bAssetInfo ? <WhImport bAssetInfo={bAssetInfo} /> : <></>;
}
Example #24
Source File: useUrlParamsLoader.tsx    From caritas-onlineBeratung-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function useUrlParamsLoader() {
	const { consultingTypeSlug } = useParams();
	const agencyId = getUrlParameter('aid');
	const consultantId = getUrlParameter('cid');

	const [consultingType, setConsultingType] =
		useState<ConsultingTypeInterface | null>(null);
	const [agency, setAgency] = useState<AgencyDataInterface | null>(null);
	const [consultant, setConsultant] =
		useState<ConsultantDataInterface | null>(null);
	const [loaded, setLoaded] = useState<boolean>(false);

	useEffect(() => {
		(async () => {
			try {
				let agency,
					consultingType = null;
				if (isNumber(agencyId)) {
					agency = await apiGetAgencyById(agencyId).catch(() => null);
				}

				if (consultantId) {
					setConsultant(await apiGetConsultant(consultantId, true));
				}

				if (consultingTypeSlug || agency) {
					consultingType = await apiGetConsultingType({
						consultingTypeSlug,
						consultingTypeId: agency?.consultingType
					});
					setConsultingType(consultingType);
				}

				if (agency?.consultingType !== consultingType?.id) {
					agency = null;
				}

				setAgency(agency);
				setLoaded(true);
			} catch (error) {
				console.log(error);
			}
		})();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [consultingTypeSlug, agencyId, consultantId]);

	return { agency, consultant, consultingType, loaded };
}
Example #25
Source File: ContractsList.tsx    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
ContractsList: React.FC<ContractsListProps> = ({
  onSelect,
  onSupportedActionSelect,
}) => {
  const { chainId } = useWeb3React();
  const { contracts } = useContractRegistry(chainId);
  const { guild_id: guildAddress } =
    useParams<{ chain_name?: string; guild_id?: string }>();
  const { isRepGuild } = useGuildImplementationTypeConfig(guildAddress);
  return (
    <Wrapper>
      <SectionWrapper>
        <SectionTitle>Core</SectionTitle>
        <ActionsButton
          onClick={() =>
            onSupportedActionSelect(SupportedAction.ERC20_TRANSFER)
          }
        >
          <ButtonLabel>
            <StyledIcon src={Vector} />
            Transfer & Mint
          </ButtonLabel>
        </ActionsButton>
        {isRepGuild ? (
          <ActionsButton
            onClick={() => onSupportedActionSelect(SupportedAction.REP_MINT)}
          >
            <ButtonLabel>
              <StyledIcon src={Mint} />
              Mint REP
            </ButtonLabel>
          </ActionsButton>
        ) : null}
      </SectionWrapper>
      <SectionWrapper>
        <SectionTitle>External Contracts</SectionTitle>
        {contracts?.map(contract => (
          <ActionsButton
            key={contract.title}
            onClick={() => onSelect(contract)}
          >
            <ButtonLabel>{contract.title}</ButtonLabel>
            <ButtonDetail>
              {contract.functions?.length}{' '}
              {contract.functions?.length > 1 ? 'Actions' : 'Action'}
            </ButtonDetail>
          </ActionsButton>
        ))}
      </SectionWrapper>
    </Wrapper>
  );
}
Example #26
Source File: GenerateCodePage.tsx    From GTAV-NativeDB with MIT License 5 votes vote down vote up
function GenerateCodePage() {
  const { language } = useParams<{ language: string }>()
  const history = useHistory()

  const onTabChange = useCallback((e: SyntheticEvent<Element, Event>, language: string) => {
    history.replace(language)
  }, [history])

  return (
    <Box sx={{ py: 2, overflow: 'hidden scroll', flexGrow: 1 }}>
      <Container maxWidth="lg">
        <Typography variant="h4" component="h1" gutterBottom>
          Generate Code
        </Typography>
        <Paper>
          <TabContext value={language}>
            <TabList onChange={onTabChange}>
              <Tab label="C++" value="cpp" />
              <Tab label="Rust" value="rs" />
              <Tab label="C# Enum" value="cs" />
              <Tab label="SHV.NET" value="shvdn" />
              <Tab label="RPH" value="rph" />
            </TabList>
            <Divider />
            <TabPanel value="cpp">
              <CPlusPlus />
            </TabPanel>
            <TabPanel value="rs">
              <Rust />
            </TabPanel>
            <TabPanel value="cs">
              <CSharpEnum />
            </TabPanel>
            <TabPanel value="shvdn">
              Soon&trade;
            </TabPanel>
            <TabPanel value="rph">
              Soon&trade;
            </TabPanel>
          </TabContext>
        </Paper>
      </Container>
    </Box>
  )
}
Example #27
Source File: app.tsx    From vorb.chat with GNU Affero General Public License v3.0 5 votes vote down vote up
RoomRoute: React.SFC<{}> = () => {
  const { room_name } = useParams();
  if(!room_name){
    return null;
  }
  return <Room room_name={room_name} />
}
Example #28
Source File: NotePage.tsx    From personal-archive with MIT License 5 votes vote down vote up
NotePage: FC = () => {
  const {id} = useParams() as any
  const history = useHistory()
  const [fetching, onReload, swapParagraphSeq, note, referencedArticles] = useNote(id)

  return (
    <NoteNavLayout
      loading={fetching}
      title={note ? note.title : undefined}
    >
      {
        note && (
          <>
            <NoteTitle
              note={note}
              onReload={onReload}
            />
            {
              note.paragraphs
                .sort((a, b) => a.seq - b.seq)
                .map(paragraph =>
                  <NoteParagraph
                    key={paragraph.id}
                    paragraph={paragraph}
                    referencedArticles={referencedArticles}
                    onMoveUp={seq => swapParagraphSeq(seq, seq - 1)}
                    onMoveDown={seq => swapParagraphSeq(seq, seq + 1)}
                    onReload={onReload}
                  />
                )
            }
            <AddButtonWrapper>
              <Button
                iconLeft={<Plus />}
                type="secondary"
                onClick={() => history.push(`/notes/${id}/paragraphs`)}
                size="small"
              />
            </AddButtonWrapper>
            <CommandPalette
              note={note}
              onReload={onReload}
            />
          </>
        )
      }
    </NoteNavLayout>
  )
}
Example #29
Source File: detail.tsx    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
DetailPage: React.FC = () => {
  const [member, setMember] = React.useState<MemberDetailEntity>(
    createDefaultMemberDetail()
  );
  const { id } = useParams();
  const classes = useStyles();

  React.useEffect(() => {
    fetch(`https://api.github.com/users/${id}`)
      .then((response) => response.json())
      .then((json) => setMember(json));
  }, []);

  return (
    <>
      <Card className={classes.root}>
        <CardActionArea>
          <CardMedia
            className={classes.media}
            image={member.avatar_url}
            title="Contemplative Reptile"
          />
          <CardContent>
            <Typography gutterBottom variant="h5" component="h2">
              {member.name}
            </Typography>
            <Typography variant="body2" color="textSecondary" component="p">
              {member.bio}
            </Typography>
          </CardContent>
        </CardActionArea>
        <CardActions>
          <Link to="/list">
            <Button size="small" color="primary">
              Back to list page
            </Button>
          </Link>
        </CardActions>
      </Card>
    </>
  );
}