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?

5
  • Why not use just to={match.url+page.id()+'/info' ? Commented Apr 18, 2019 at 6: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 Commented Apr 18, 2019 at 6: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? Commented Apr 18, 2019 at 6: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. Commented Apr 18, 2019 at 6:48
  • Check the answer if it fits your goals Commented Apr 18, 2019 at 7:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.