1

If my url path starts with a /-IDNUMBER, I want the react-router to render the Home Component. For example if the URL is:

/-MX9EnU6aOtENtdQxLvF or /-MX9F3z22XrMjlgEAHUI it should render the Home Component. I assume the best way to do this is to use Regex (let me know if there is a better way). Here is what I tried:

<Route path="/^-" component={Home} />. This is not working, I tried other variations which also don't work. Please let me know how to fix this.

3
  • I think this Shaya's answer solves your problem. Commented Mar 31, 2021 at 22:55
  • I think this solves your problem! Commented Mar 31, 2021 at 22:56
  • Hi! Thanks for finding that, I'm still having problems with getting the Regex to work. I don't know how long the ID Number can be, it can be as long as possible. Therefore I need a different answer. Commented Mar 31, 2021 at 23:12

1 Answer 1

1

I guess you could try something like:

const idRegex = '([0-9a-zA-Z]*)';

...

<Route path={`/-${idRegex}`} component={Home} />

I couldn't find the official documentation, but basically, if you open () in a path string, you can include a Regex expression in it. So, I basically wrote this simple Regex Expression that is going to match every number, letter and especial character.

So finally, when you add path={`/-${idRegex}`}, it's going to consider a a router as you need, /-USERID, and render the proper Component. The final Path String is going to be /-([0-9a-zA-Z]*).

I hope it's clear enough, and you can apply it furthermore to some other situations.

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

2 Comments

Thank you for your answer! It works. Can you please explain how it works.
I just updated my answer. I hope it clarifies.

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.