5

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.

Roland
  • 885
  • 3
  • 12
  • 16
  • 1
    I suppose it still isn't clear, do you want the match params, i.e. the values, or the path pattern used? https://reactrouter.com/web/api/match The `path` is the path pattern used to match. Reverse the order of your defined routes so you try to match *more* specific paths *before* less specific paths. – Drew Reese Oct 11 '20 at 23:03
  • @DrewReese The match params. I've seen the documentation for match, but didn't pay full attention. I've seen that you can give an array of paths. I put them in reverse order like you said (the more complex one first) and it did the job. Thank you for your answer :) – Roland Oct 11 '20 at 23:09
  • Right, ok. Great, glad that worked out for you. – Drew Reese Oct 11 '20 at 23:13
  • Does this answer your question? [react-router v6: get path pattern for current route](https://stackoverflow.com/questions/66265608/react-router-v6-get-path-pattern-for-current-route) – mahan Mar 24 '23 at 12:52

3 Answers3

4

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.

  • 3
    this won't do anything, because it's riddled with errors.... – flaky Jun 27 '22 at 13:57
  • Don't do this. React hooks should only be called in React components or custom hooks. Refer to the rules of hooks: https://legacy.reactjs.org/docs/hooks-rules.html – JnsBne Apr 06 '23 at 09:06
0

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"

-1

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;
};
Stephen Burke
  • 389
  • 2
  • 13