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

Viewed 1421

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")?

3 Answers

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

If you do router.push("/page1/page2/next-page"), it should work. I think you need to specify the full path, I don't see anything wrong in doing so

if you want to append something to an existing path, you should be able to do something like

const location = useLocation()
const currentPath = location.pathname // to get current route
router.push(`${currentPath}/next-page`)

THis is a sudo-code, so you may need to tweak it a bit for proper syntax

Related