Reputation: 965
How can I get the current route? And I mean route, not path
After entering manually an url, in the root component of my app App.tsx I want to get some options from the url
I tried this:
const match = useRouteMatch({
path: location.pathname,
strict: true,
sensitive: true
});
But it doesn't give me the props.
So I need something like:
const match = useRouteMatch({
path: `/:lang/:car`,
strict: true,
sensitive: true
});
But I need to get that path(route) somehow dynamically.
I also tried to use useParams from react-router-dom
. And do something like:
const { lang } = useParams<ParamTypes>();
This also doesn't work if I write it in the main component App.tsx. Only in a component that specifically has /:lang
in it's route.
If this wasn't clear I'll put an example.
Let's say I have these routes:
<Route path='/'/>
<Route path='/:lang'/>
<Route path='/:lang/:bookId'/>
<Route path='/:lang/:bookId/:author'/>
And I enter manually the url baseurl/en/21
In App.tsx how can I get the lang and the bookId ?
I should have something like:
const match = useRouteMatch({
path: `/:lang/:bookId`,
strict: true,
sensitive: true
});
But say I enter the url baseurl/en/21/some-name
, then the match
const will be null. And in this case I also would want to get author
. However I don't know what url will the user be typing. So this is why I need to get the route dynamically.
Upvotes: 6
Views: 19060
Reputation: 459
Here's my React Code written in TS to get a split pathname:
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
/**
* @function useFindPath
* @param pathIdx
* @description - returns a string from the current route based on the path split by `/`.
* @returns string
* @example:
* - pathIdx = 2
* - path = /projects/foo-bar
* - return = 'foo-bar'
*/
export const useFindPath = (pathIdx?: number): string => {
const location = useLocation();
const [currentPath, setCurrentPath] = useState<string>();
useEffect(() => {
const path: string = location.pathname;
if (pathIdx) {
const splitPath: string[] = location.pathname.split('/');
setCurrentPath(splitPath[pathIdx]);
} else {
setCurrentPath(path);
}
}, [location, pathIdx]);
return currentPath as string;
};
Upvotes: -1
Reputation: 7
try this hook:
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
export const useFindPath = () => {
const location = useLocation();
const [currentPath, setCurrentPath] = useState();
useEffect(() => {
setCurrentPath(location.pathname);
}, [location]);
return currentPath;
};
usage:
const path = useFindPath();
Output: e.g."/about" if current url is "http://localhost:3000/about"
Upvotes: 0
Reputation: 91
Try this:
const findPath() {
const location = useLocation();
useEffect(() => {
const currentPath = location.pathname;
}, [location]);
return currentPath;
}
This will return the entire path by using the useLocation hook and it will re-render every time the url is changed because of the useEffect.
Upvotes: 3