Search code examples
reactjsreact-routerreact-router-dom

React Router: How to properly append to route/url without replacing anything?


How do I append to the route with react router?

Let's say the current route is /page1/page2 and I want to route to /page1/page2/next-page

first I get the router

const router = useHistory();

When I use push like this

router.push("next-page");

It routes to /page1/next-page.

When I use add a / like this

router.push("/next-page");

It routes to /next-page

I also tried something like this

router.push(`${router.location.pathname}/next-page`)

But the problem this way is, when I'm currently at /page1/page2/, I end up at /page1/page2//next-page with two //.

Is there a good way to solve this without having to write the complete route like router.push("/page1/page2/next-page")?


Solution

  • What I ended up doing is defining a function that removes an / form the url if there

    export const removeSlashSuffix = (input)  => {
        if (input.charAt(input.length - 1) === "/") {
            return input.substr(0, input.length - 1)
        } else {
            return input;
        }
    }
    

    and then route like this

    router.push(`${removeSlashSuffix(router.location.pathname)}/nest-page`)
    

    This way I get no issues with routes that resolve in url with // in it.

    This is somewhat of a hacky solution and I wish react-router-dom would support this out of the box but it doesn't seem like it does