Tarun Ravi
Tarun Ravi

Reputation: 169

React Router With Regex

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.

Upvotes: 1

Views: 1150

Answers (1)

filipemelo032
filipemelo032

Reputation: 133

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.

Upvotes: 1

Related Questions