0

There's a potential bug I found in react router. In my component, I do this:

if(this.props.location.pathname === "/home")

to check whether the user is at a path. It can be buggy, because the above condition is false if the user enters the URL manually, like example.com/home/

How to handle this case? It's ugly to do multiple checking like this:

if(this.props.location.pathname === "/home" || this.props.location.pathname === "/home/"))

Any suggestions on how I could do this in a better and cleaner way?

Dzenis H.
  • 4,658
  • 2
  • 17
  • 39
Alisa T Morgan
  • 527
  • 1
  • 5
  • 12

4 Answers4

1

Depending on what you want to achieve you can mix exact and strict attributes. I suggest looking into this ;)

strict: bool

Match from strictly; equivalent to Route.strict.

// this will match both /home and /home/

<Route exact path="/foo" strict={false} component={foo} />

For future references here's a link to official docs.

Dzenis H.
  • 4,658
  • 2
  • 17
  • 39
  • default the strict is `undefined` right? why do I need to use strict in my case? – Alisa T Morgan Oct 05 '18 at 05:33
  • 2
    This is the correct answer and should be used accepted instead of the currently accepted answer of pattern matching. It's literally what you want @AlisaTMorgan. – nbokmans Oct 05 '18 at 07:45
  • @AlisaTMorgan -Well, your "case" is kinda strange, and in 99,99% cases that type of behavior/ solution is not required. Since you asked, I offered help and show you that nice people @ React-Router team are doing a great job, so there's a nice solution for your case too. Usually if a user types in (manually) an additional slash "/" it gets removed automatically by the browser. `undefined` means just that -it's not present, but if you do it as I showed you, the job gets done correctly and easily. I suggest visiting the link I provider for further references. Have a nice day. @nbokmans Thank you – Dzenis H. Oct 05 '18 at 17:07
  • user go to example.com/dashboard, and the user can also go to example.com/dashboard/ – Alisa T Morgan Oct 06 '18 at 17:37
  • No, I understand you, completely. I'm just saying adding this `strict={false}` is clean, easy, and should solve the problem for you. Happy hacking :) – Dzenis H. Oct 07 '18 at 08:04
0

Have you considered using:

this.props.match.path
johnnylak
  • 327
  • 3
  • 8
0

Try

if (this.props.location.pathname.match(/^\/home\/?$/g))

That will exactly match either /home or /home/

Daniel Williams
  • 1,947
  • 3
  • 23
  • 40
0

You can try using indexOf:

if (this.props.location.indexOf("home") >= 1)

const URL = ["home", "/home", "/home/", "/home/about", "/about", "/logout", "/login/home"];

URL.forEach(url => {
 const isMatch = url.indexOf("home") >= 1 
 console.log(`${url} is a match? ${isMatch}`);
})

The caveat (or benefit) is that it can match to any URL combination with /home in it (as shown above).

Matt Carlotta
  • 13,627
  • 3
  • 24
  • 39