react-router-dom#useParams JavaScript 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: deck-state.jsx From MDXP with MIT License | 6 votes |
DeckState = ({children, slide, step, preview = false}) => {
const params = useParams();
const rootContext = useRoot();
const slideNum = (slide !== undefined) ? parseInt(slide) || 0 : parseInt(params.slide) || 0;
const stepNum = (step !== undefined) ? parseInt(step) || 0 : parseInt(params.step) || 0;
const slideIndex = getIndex(slideNum, rootContext.slideLength);
const [state, setState] = useMerger({
mode: rootContext.mode,
slideLength: rootContext.slideLength,
slideIndex,
stepLength: 1,
stepIndex: 0,
rawStepIndex: stepNum,
preview
});
useLayoutEffect(() => {
if (slideIndex !== state.slideIndex) {
setState({slideIndex, rawStepIndex: stepNum, stepIndex: 0, stepLength: 1});
} else if ((stepNum !== state.rawStepIndex)) {
setState({rawStepIndex: stepNum});
}
}, [slideIndex, stepNum]);
useLayoutEffect(() => {
if (rootContext.mode !== state.mode) {
setState({mode: rootContext.mode});
}
}, [rootContext.mode]);
return (
<DeckContext.Provider value={[state, setState]}>
{children}
</DeckContext.Provider>
);
}
Example #2
Source File: User.jsx From react_53 with MIT License | 6 votes |
function User() {
const { userUrl } = useParams();
const user = users.find((item) => item.url === userUrl);
const { fullName, info } = user;
return (
<div className={styles.userContent}>
<div>
<h3>{fullName}</h3>
<div>{info}</div>
</div>
</div>
);
}
Example #3
Source File: generic-redirect.jsx From neighborhood-chef-fe with MIT License | 6 votes |
function GenericRedirect(props) {
const { push } = useHistory();
const { redirect_path } = useParams();
const getInitialUserDataAndRedirectOnSuccess = () => {
const token = ls.get("access_token");
const decodedToken = jwt(token).sub;
axiosWithAuth()({
url: `${process.env.REACT_APP_BASE_URL}/graphql`,
method: "post",
data: {
query: print(USER_BY_EMAIL),
variables: { input: { email: decodedToken } },
},
}).then((res) => {
sessionStorage.setItem(
"user",
JSON.stringify(res.data.data.getUserByEmail)
);
push(`/${redirect_path}`);
});
};
if (!ls.get("access_token")) {
push(`/generic-redirect/${redirect_path}`);
} else {
getInitialUserDataAndRedirectOnSuccess();
}
return null;
}
Example #4
Source File: Resume.js From resumeker-fe with MIT License | 6 votes |
function ResumeComponent(props) {
const params = useParams();
const classes = useStyles();
console.log(params.draftID, "\n DraftID");
const { data, loading, error } = useQuery(GET_DRAFT_QUERY, {
variables: { draftID: params.draftID },
});
if (loading) return <div>Loading... </div>;
if (error) return <div>Error: {error}</div>;
console.log(data, "resume query response");
const { getDraft } = data;
return (
<div className={classes.wrapper}>
<Paper className={classes.paper}>
<Grid>
<div className={classes.name}>{getDraft.name}</div>
<div>{getDraft.email}</div>
</Grid>
<Grid>Education</Grid>
<Grid>Jobs</Grid>
<Grid>Projects</Grid>
<Grid>Tech Skills</Grid>
<Grid>General Skills</Grid>
<Grid>Languages</Grid>
<Grid>Hobbies</Grid>
</Paper>
</div>
);
}
Example #5
Source File: ClientBoard.js From schematic-capture-fe with MIT License | 6 votes |
Board = () => {
const dispatch = useDispatch()
const params = useParams()
const clients = useSelector(state => state.dashboard.clients)
useEffect(() => {
setCurrentClient(clients, params.id, dispatch)
}, [clients, params.id, dispatch])
return (
<>
<Header />
</>
)
}
Example #6
Source File: Invite.js From video-journal-for-teams-fe with MIT License | 6 votes |
Invite = ({ fetchInvite, isLoading }) => {
const { invite } = useParams();
const history = useHistory();
useEffect(() => {
fetchInvite(invite);
}, [invite, fetchInvite]);
return (
<div>
{
isLoading ? <LoadingView /> : history.push("/user-dashboard")
// : <Redirect to='/register' />
}
</div>
);
}
Example #7
Source File: Article.jsx From genshin with MIT License | 6 votes |
Article = () => {
const { slug } = useParams();
const data = useSelector(selectArticlebySlug);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getArticle(slug));
}, []);
if (!data[0]) {
return <NotFoundAtom />;
}
const { title, content, date } = data[0];
return (
<>
<h1>{title}</h1>
<p>{new Date(date).toLocaleDateString()}</p>
<p>{content}</p>
</>
);
}
Example #8
Source File: EditPatchNoteWrapper.js From ponce-tournois-mario-kart with MIT License | 6 votes |
function EditPatchNoteWrapper() {
const { patchNoteId } = useParams();
const { loading } = useSelector((state) => state.patchNotes);
const patchNote = useSelector((state) =>
getPatchNoteById(state, patchNoteId)
);
return (
<div className="app__container">
{loading ? (
<PatchNoteFormSkeleton />
) : !patchNote ? (
<Row justify="center">
<Col xs="content">
<div className="formMessage formMessage__error">
Ce patch note n'existe pas
</div>
</Col>
</Row>
) : (
<EditPatchNoteForm patchNote={patchNote} />
)}
</div>
);
}
Example #9
Source File: NeedData.js From e-Pola with MIT License | 6 votes |
function NeedData() {
const { needId } = useParams()
// Create listener for needs
useFirestoreConnect([{ collection: 'needs', doc: needId }])
// Get needs from redux state
const need = useSelector(
({
firestore: {
data: { needs }
}
}) => needs && needs[needId]
)
// Show loading spinner while need is loading
if (!isLoaded(need)) {
return <LoadingSpinner />
}
return (
<CardContent>
<Typography component="h2">{(need && need.name) || 'Need'}</Typography>
<Typography>{needId}</Typography>
<div style={{ marginTop: '4rem' }}>
<pre>{JSON.stringify(need, null, 2)}</pre>
</div>
</CardContent>
)
}
Example #10
Source File: queenRedirect.js From Queen with MIT License | 6 votes |
QueenRedirect = () => {
const { standalone } = useContext(AppContext);
const { readonly, idSU } = useParams();
const getSurveyUnit = useGetSurveyUnit();
const [idQuestionnaire, setIdQuestionnaire] = useState(null);
const [errorMessage, setErrorMessage] = useState(null);
useEffect(() => {
if (!idQuestionnaire && !errorMessage) {
const load = async () => {
const response = await getSurveyUnit(idSU, standalone);
if (!response.error && response.surveyUnit && response.surveyUnit.questionnaireId) {
setIdQuestionnaire(response.surveyUnit.questionnaireId);
} else setErrorMessage(`${D.failedToLoadSurveyUnit} ${idSU}.`);
};
load();
}
}, [getSurveyUnit, errorMessage, idQuestionnaire, idSU, standalone]);
return (
<>
{errorMessage && <Error message={errorMessage} />}
{!errorMessage && !idQuestionnaire && <Preloader message={D.waintingData} />}
{!errorMessage && idQuestionnaire && (
<Redirect
to={`/queen${
readonly ? `/${readonly}` : ''
}/questionnaire/${idQuestionnaire}/survey-unit/${idSU}`}
/>
)}
</>
);
}
Example #11
Source File: Social.jsx From saasgear with MIT License | 6 votes |
export default function Social() {
const query = getQueryParam();
const code = query.get('code');
const { provider } = useParams();
const dispatch = useDispatch();
const history = useHistory();
const { data, loading, error } = useQuery(socialLoginQuery, {
variables: { provider: provider.toUpperCase(), code },
});
useEffect(() => {
if (!loading && data?.loginBySocial) {
history.replace('/');
}
}, [data, loading, error]);
useEffect(() => {
if (error) {
dispatch(toggleToastError({ error: error.message }));
history.push('/auth/signin');
}
return () => {
dispatch(toggleToastError({ error: null }));
};
}, [error]);
return loading ? (
<div>{provider}</div>
) : (
!error && <FormRegister data={data?.loginBySocial} />
);
}
Example #12
Source File: Autor.js From master-en-code-g2 with MIT License | 6 votes |
function Autor() {
const params = useParams();
console.log(params);
return (
<>
<h1>Autor</h1>
<h2>Estoy en una URL dinámica!</h2>
<h3>Mostrando el autor {params.idAutor}</h3>
</>
)
}
Example #13
Source File: index.js From ocp-advisor-frontend with Apache License 2.0 | 6 votes |
RecommendationWrapper = () => {
const intl = useIntl();
const rule = useGetRuleByIdQuery(useParams().recommendationId);
const ack = useGetRecAcksQuery({ ruleId: useParams().recommendationId });
if (rule.isSuccess && rule.data?.content?.description) {
const subnav = `${rule.data.content.description} - Recommendations`;
insights.chrome.updateDocumentTitle(
intl.formatMessage(messages.documentTitle, { subnav })
);
}
const clusters = useGetAffectedClustersQuery(useParams().recommendationId);
useEffect(() => {
rule.refetch();
}, [useParams().recommendationId]);
return (
<Recommendation
rule={rule}
ack={ack}
clusters={clusters}
match={useRouteMatch()}
/>
);
}
Example #14
Source File: ShowClassTable.jsx From course-plus with Apache License 2.0 | 6 votes |
export default function () {
const { semester } = useParams()
return (
<div>
<Link
to={`/${semester}/classtable`}
className='row text-reset jumbotron jumbotron-fluid d-block d-md-none px-1 py-3 text-center my-0 course-button'
>
<span className='h4'>显示本学期课表</span>
</Link>
<p className='text-muted small text-center d-md-none'>
请使用 PC 访问以使用完整功能。
</p>
</div>
)
}
Example #15
Source File: ASDProjectPage.js From sutdmc-landing with MIT License | 6 votes |
ASDProjectPageComp = () => {
let { id } = useParams();
const project = projectDetails[id];
return (
<PageBase>
<PageHeader>{project.title}</PageHeader>
<ContentWrapper>{project.content}</ContentWrapper>
</PageBase>
);
}
Example #16
Source File: PostPage.js From instaclone with Apache License 2.0 | 6 votes |
PostPage = () => {
const { postId } = useParams();
return (
<Fragment>
<MobileHeader backArrow>
<h3 className="heading-3">Post</h3>
{/* Empty element to keep grid happy */}
<div></div>
</MobileHeader>
<main className="post-page grid">
<PostDialog className="border-grey-2" postId={postId} />
</main>
</Fragment>
);
}
Example #17
Source File: Speakers.jsx From Consuming-GraphqL-Apollo with MIT License | 6 votes |
SpeakerDetails = () => {
const { speaker_id } = useParams();
const { loading, error, data } = useQuery(SPEAKER_BY_ID, {
variables: { id: speaker_id },
});
if (loading) return <p>Loading speaker...</p>
if (error) return <p>Error loading speaker!</p>
const speaker = data.speakerById;
const { id, name, bio, sessions } = speaker;
return (
<div key={id} className="col-xs-12" style={{ padding: 5 }}>
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">{name}</h3>
</div>
<div className="panel-body">
<h5>{bio}</h5>
</div>
<div className="panel-footer">
{sessions.map(({ id, title }) => (
<span key={id} style={{ padding: 5 }}>
"{title}"
</span>
))}
</div>
</div>
</div>
);
}
Example #18
Source File: PackDetails.page.js From crypto-dappy with Apache License 2.0 | 6 votes |
export default function PackDetails() {
const [pack, setPack] = useState(null)
const [dappies, setDappies] = useState([])
const { packID } = useParams()
const { fetchDappiesOfPack, mintFromPack, fetchPackDetails } = useDappyPacks()
useEffect(() => {
fetchDappies()
//eslint-disable-next-line
}, [])
const fetchDappies = async () => {
let dappiesOfPack = await fetchDappiesOfPack(parseInt(packID.replace("Pack", "")))
setDappies(dappiesOfPack)
let packDetails = await fetchPackDetails(parseInt(packID.replace("Pack", "")))
setPack(packDetails)
}
if (!pack) return <Spinner />
return (
<div className="packdetails__wrapper">
<img className="pack__img" src={`${process.env.PUBLIC_URL}/assets/${packID}.png`} alt='Pack' />
<div className="pack__content">
<h3 className="app__title">{pack?.name}</h3>
<div
onClick={() => mintFromPack(packID, dappies, pack?.price)}
className="btn btn-bordered btn-light"
style={{ width: "60%", margin: "0 auto", display: "flex", justifyContent: "center" }}>
<i className="ri-shopping-cart-fill" style={{ fontSize: "1.2rem", marginRight: ".2rem" }}></i> {parseInt(pack?.price)} FUSD
</div>
<p>Dappies included:</p>
<p>
{dappies.map((d, i) => ` #${d} `)}
</p>
</div>
</div>
)
}
Example #19
Source File: FormRouter.js From datapass with GNU Affero General Public License v3.0 | 6 votes |
FormRouter = () => {
const { targetApi } = useParams();
const TargetApiComponent =
DATA_PROVIDER_PARAMETERS[targetApi.replace(/-/g, '_')]?.component;
const { goBackToList } = useListItemNavigation();
if (!TargetApiComponent) {
setTimeout(() => goBackToList(), 3000);
return <NotFound />;
}
return (
<AuthRequired>
<TargetApiComponent />
</AuthRequired>
);
}
Example #20
Source File: MovieDetails.js From Lambda with MIT License | 6 votes |
// import { movies } from '../data/movieData';
function MovieDetails(props) {
const { id } = useParams();
const choice = props.movies.find(
(movie) => movie.id.toString() === id.toString()
);
if (!choice) {
return <Redirect to="/" />;
}
return (
<div className="comp purple">
<h1>{choice.title}</h1>
<p style={{ fontStyle: "italic" }}>{choice.description}</p>
</div>
);
}
Example #21
Source File: ColorDetails.js From Learning-Redux with MIT License | 6 votes |
export function ColorDetails() {
let { id } = useParams();
let { colors } = useColors();
let foundColor = colors.find((color) => color.id === id);
return (
<div>
<div
style={{
backgroundColor: foundColor.color,
height: 100,
width: 100,
}}
></div>
<h1>{foundColor.title}</h1>
<h1>{foundColor.color}</h1>
</div>
);
}
Example #22
Source File: index.js From relay_04 with MIT License | 6 votes |
function ViewText() {
const { id } = useParams();
const dispatch = useDispatch();
const { post } = useSelector((state) => state.post);
useEffect(() => {
async function fetchData() {
const response = await loadPostAPI(id);
dispatch(actions.loadPost(response.data));
}
fetchData();
}, [dispatch, id]);
return (
<div className = "viewText_main">
<div className="viewText_back"><Link to='/post'> 뒤로가기 </Link></div>
<div className="viewText_title">{post.title}</div>
<div className="viewText_writer">{post?.User?.userid}</div>
<div className="viewText_content">{post.content}</div>
</div>
);
}
Example #23
Source File: index.js From relay_09 with MIT License | 6 votes |
StreamingPage = () => {
let history = useHistory();
const { videoNum } = useParams();
const videoList = useSelector((state) => state.video.videoList);
const video = videoList && videoList.filter((v) => v.id === videoNum)[0];
return (
<>
<MyNav />
{videoList.length ? (
<Wrapper>
<Video className="video" controls autoPlay width="500">
<source src={video.video} />
Sorry, your browser doesn't support embedded videos.
</Video>
<TitleWrapper>
<Text>{video.title}</Text>
<ReportButton videoUrl={video.video} className="Reportbutton" />
</TitleWrapper>
</Wrapper>
) : (
history.push(`/components`)
)}
</>
);
}
Example #24
Source File: Detail.jsx From sitepoint-books-firebase with MIT License | 6 votes |
function ScreenBookDetail() {
const { id } = useParams()
const { data, isLoading, error, status } = useQuery(
['book', { id }],
BookService.getOne
)
return (
<>
<PageHeading title="Book Detail" />
{error && <Alert type="error" message={error.message} />}
{isLoading && (
<Alert
type="info"
message="Loading..."
innerClass="animate animate-pulse"
/>
)}
{status === 'success' && <BookDetail book={data} />}
</>
)
}
Example #25
Source File: BaseLayout.js From clone-instagram-ui with MIT License | 6 votes |
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: {
...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 #26
Source File: index.js From whaticket with MIT License | 6 votes |
Chat = () => {
const classes = useStyles();
const { ticketId } = useParams();
return (
<div className={classes.chatContainer}>
<div className={classes.chatPapper}>
<Grid container spacing={0}>
{/* <Grid item xs={4} className={classes.contactsWrapper}> */}
<Grid
item
xs={12}
md={4}
className={
ticketId ? classes.contactsWrapperSmall : classes.contactsWrapper
}
>
<TicketsManager />
</Grid>
<Grid item xs={12} md={8} className={classes.messagessWrapper}>
{/* <Grid item xs={8} className={classes.messagessWrapper}> */}
{ticketId ? (
<>
<Ticket />
</>
) : (
<Hidden only={["sm", "xs"]}>
<Paper className={classes.welcomeMsg}>
{/* <Paper square variant="outlined" className={classes.welcomeMsg}> */}
<span>{i18n.t("chat.noTicketMessage")}</span>
</Paper>
</Hidden>
)}
</Grid>
</Grid>
</div>
</div>
);
}
Example #27
Source File: EditPerson.jsx From maps with MIT License | 6 votes |
EditPerson = (props) => {
const [person, setPerson] = useState(props.person);
const { id } = useParams();
const [open, close] = useAlert();
useEffect(() => {
if (person == null) {
PersonService.getById(id, setPerson);
}
}, [props]);
if (person) {
return (
<>
<h5>Edit Person Info</h5>
<PersonFormContainer person={person} />
</>
);
} else {
return <></>;
}
}
Example #28
Source File: CategoryContainer.js From covid-break-master with MIT License | 6 votes |
export default function CategoryContainer(props) {
const { id } = useParams()
const match = useRouteMatch()
const categories = []
for(let obj in props.parts) {
categories.push({name: obj, image: props.parts[obj][0].url})
}
const [modal, setModal] = useState(false);
const [displayedItem, setDisplayedItem] = useState()
const toggleModal = () => setModal(!modal);
return (
<CategoryDiv>
{categories.length > 0 && props.parts[`${categories[id].name}`].map((item, index) => {
return (
<>
<ItemDiv onClick={() => {
toggleModal()
setDisplayedItem(item)
}}>
<h3>{item.name}</h3>
<img style={{
maxWidth: "100%",
maxHeight: "173px"
}} src={item.url} />
<p>{item.price}</p>
</ItemDiv>
</>
)
})}
{displayedItem ? <PartsCard toggleModal={toggleModal} modal={modal} part={displayedItem} cart={props.cart} cartRemove={props.cartRemove} cartAdd={props.cartAdd} /> : null}
</CategoryDiv>
)
}
Example #29
Source File: Catalog.js From clayma-store with MIT License | 6 votes |
export default function Catalog(props) {
const {id,action} =useParams();
let selectedProduct = "";
if (id != null) {
selectedProduct = data.filter((product) => product.id === id);
}
return (
<div>
<TopBanner />
<NavBar />
<HeroImage />
<ProductDetails product={selectedProduct} key={selectedProduct.id} action={action}/>
<Footer />
</div>
);
}