Get current route for react-router

Viewed 8287

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.

2 Answers

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.

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"

Related