reactjsreact-routerreact-router-v4react-router-domreact-routing

React router: How to handle trailing / in match.url when building Links?


I've been building Links in my React app (using react-router-dom 4.3.1) using code like the following:

const { match } = this.props;
...
pages.map(page =>
    <Link to={match.url+'/'+page.id()+'/info'}>
        Go to info page for {page.title()}
    </Link>)

as this seems to be the recommended practice (e.g. see ${match.url}/components https://reacttraining.com/react-router/web/guides/quick-start/example-nested-routing).

The problem I'm having:

If I'm at the following path:

/app/home

the links generated by the above are as expected:

But if I load this (subtlely different) path (notice the trailing /):

/app/home/

then the generated links are wrong (notice the double / after home):

In other words, the problem is that sometimes there's a trailing / and sometimes there is not.

When I'm building a link, do I need to manually check for a trailing / every time and strip it if it's there? Or is there some better best practice that I'm perhaps missing?


Solution

  • Discard a trailing / provided by the user:

    const {match} = this.props;
    let len = match.url.length;
    match.url = (match.url[len - 1] === "/") ? match.url.substring(0, len-1) : match.url;
    
    ...
    
    pages.map(page =>
    <Link to={match.url+'/'+page.id()+'/info'}>
        Go to info page for {page.title()}
    </Link>)
    

    Alternately you can add if its missing as well:

    match.url = (match.url[len - 1] === "/") ? match.url : match.url + "/";
    
    pages....
        <Link to={match.url + page.id() ....}
    ... 
    

    I think it's easier to add a missing one rather than discarding an existing one.