Crocsx
Crocsx

Reputation: 7609

Get router value from url in react

I have a react app, and a component that is supposed to load a set of value of the url

        <PersistGate persistor={rootStore.persistor}>
            <Router history={history}>
                <ErrorBoundary>
                  <Preloader history={history} /> <== this need to read the url
                  <PasswordChecker></PasswordChecker>
                  <RouteDispatcher></RouteDispatcher> <== this contain the list of routes
                </ErrorBoundary>
            </Router>
        </PersistGate>

In my RouteDispatcher path I have setup the route like this :

    <BrowserRouter>
      <Switch>
        <PrivateRoute path="/ws/:ws/pj/:pj/ds/:ds" component={HomeDatastore} />
        <PrivateRoute path="/ws/:ws/pj/:pj" component={HomeProject} />
        <PrivateRoute path="/ws/:ws" component={HomeWorkspace} />
      </Switch>
    </BrowserRouter>

how would I get the value of ws=:ws pj=:pj etc...

I was thinking of doing it with a regex, but I wonder if there is a better way. Preloader is outside the routeDispatcher, so I don't seem to find a good way to get the value.

Upvotes: 1

Views: 216

Answers (2)

joy08
joy08

Reputation: 9652

May be try using useParams() hook. It gives you a way to access the URL params

Reference: https://blog.logrocket.com/react-router-hooks-will-make-your-component-cleaner/

Sandbox: https://codesandbox.io/s/react-router-useparams-hooks-q8g37

This might help you get started with it

import { useParams } from "react-router-dom";

function ComponentName() {
  let params = useParams();
  return (
    <div>
     {params.ws}
     {params.pj}
    </div>
  );
}

Upvotes: 1

Kirill Skomarovskiy
Kirill Skomarovskiy

Reputation: 1565

React router provides params into the component. Check props.match.params. I see that you have a custom component PrivateRoute so first check props in PrivateRoute.

Upvotes: 2

Related Questions