1

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:

  • /app/home/1/info
  • /app/home/2/info
  • /app/home/3/info
  • etc.

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

/app/home/

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

  • /app/home//1/info
  • /app/home//2/info
  • /app/home//3/info
  • etc.

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?

Tom G
  • 2,025
  • 3
  • 21
  • 32
  • Why not use just `to={match.url+page.id()+'/info'` ? – Arup Rakshit Apr 18 '19 at 06:39
  • As you adding a trailing `'/'` in your link, it is better to use `/app/home` for the `match.url`. If you want to use `/app/home/` then remove the `'/'` from the Link – Dblaze47 Apr 18 '19 at 06:39
  • The problem is that sometimes there is a trailing `/` and sometimes there isn't. Presumably my app should work in both situations? Or I should just ignore one of them? – Tom G Apr 18 '19 at 06:44
  • @Dblaze47 it's not that I want to use one or the other - it's a URL in the browser, so the user can easily change it to either. – Tom G Apr 18 '19 at 06:48
  • Check the answer if it fits your goals – Dblaze47 Apr 18 '19 at 07:12

1 Answers1

1

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.

Dblaze47
  • 868
  • 5
  • 17