Home > OS >  React Router URL parameter in URL format
React Router URL parameter in URL format

Time:11-20

Not sure how to really word the question, but I have tried and not been able to do this properly. I am going to assume that I have to use some sort of regular expression but again, my previous attempts have failed.

What I am looking to do is use react router on specific routes, but I want the URL parameters to be a path itself. For example. I want to have something like

<HashRouter>
  <Switch>
    <Route path="/page/:thePath" component={ThePageComponent} />
  </Switch>
</HashRouter>

So if I visit a path like http://localhost:9000/#/page/some/random/path/here I can load ThePageComponent and access the URL parameters to get /some/random/path but it seems to not be able to find the route when I try to set this up.

Can someone point me in the right direction of the docs so I can learn how to do this? I am relatively new to react and react-router so I may be missing something simple but I can't for the life of me figure this out.

Thank you


Based on the accepted answer below, I was able to get it working. Its a little different than what I had in the example, but still works

<HashRouter>
  <Routes>
    <Route path="/*" element={<App/>} />
  </Routes>
</HashRouter>

Then in my App component

const parameters= useParams();
console.log("params ", parameters)

So visiting http://localhost:9000/#/Logic1/Testing will result in the following payload

{
    "*": "Logic1/Testing"
}

CodePudding user response:

Use the Edit react-router-url-parameter-in-url-format

If you want to learn more about path matching, RRDv5 uses [email protected] to convert the specified path string into a regex used for route matching.

  • Related