You mention the useLocation
hook so I'll assume you are using react-router
or react-router-dom
. You can use the useMatch
hook to test a path pattern, and if there is a match a match object is returned. The match object has a params
property that will have any path params available on it.
declare function useMatch<
ParamKey extends ParamParseKey<Path>,
Path extends string
>(
pattern: PathPattern<Path> | Path
): PathMatch<ParamKey> | null;
interface PathMatch<ParamKey extends string = string> {
params: Params<ParamKey>;
pathname: string;
pattern: PathPattern;
}
Example:
Test path: "/Test/marks"
import { useMatch } from 'react-router-dom';
...
const match = useMatch("/:key/marks");
console.log(match?.params?.key); // "Test"
...
If the component that needs to access that part of the URL path is already rendered as part of the normal routing, e.g. on a route rendered on path "/:key/marks"
, it could also just use the useParams
hook directly to access the key
path parameter.
Example:
<Route path="/:key/marks" element={.....} />
And in the route component on test path: "/Test/marks"
const { key } = useParams(); // "Test"