I'm using react and react-router-dom.
I want to get the value of :groupId in the User component.
In the Groups component, I can use useParams to get the groupId, but I want to get the groupId in the User component and pass it to the Groups component as a props.
import React from 'react';
import {Route, useHistory, useParams} from 'react-router-dom';
import User from 'components/User';
import useSearchParams from './useSearchParams';
export const User = () => {
const {query, setQuery} = useSearchParams();
const history = useHistory();
const {userId} = useParams<{
userId: string;
}>();
return (
<div>
<Route path="/users/:userId/groups/:groupId">
<Groups
onClose={() =>
history.push(`/users/${userId}/groups${location.search}`)
}
/>
</Route>
</div>
);
};
import React from 'react';
interface Props {
groupId?: string;
onClose: () => void;
}
export const Groups = ({groupId, onClose}: Props) => {
const params = useParams<{prospectId: string}>();
console.log(params)
return (
<div>
</div>
);
};
CodePudding user response:
You can even pass ids as a state in history.push(location, state) and update groups component to get the group ids from the state instead of passing group ids as part of the url
CodePudding user response:
you can get groupId by split pathName and get the last item
import React from 'react';
import {Route, useHistory, useParams,useLocation} from 'react-router-dom';
import User from 'components/User';
import useSearchParams from './useSearchParams';
export const User = () => {
const {query, setQuery} = useSearchParams();
const history = useHistory();
const {userId} = useParams<{
userId: string;
}>();
const location = useLocation();
const groupId = location.pathname.split("/").pop();
return (
<div>
<Route path="/users/:userId/groups/:groupId">
<Groups groupId ={groupId }
onClose={() =>
history.push(`/users/${userId}/groups${location.search}`)
}
/>
</Route>
</div>
);
};
