5

Is there a way to shorten the path length when routes are passed through components in React Router? For example, in App.js:

<Switch>
  <Route exact path="/" component={Landing} />
  <Route exact path="/login" component={Login} />
  <PrivateRoute path="/main" component={Main} />
  <Route component={NotFound} />
</Switch>

And in Main.js component:

<Switch>
    <Route exact path="/main" component={Dashboard} />
    <Route exact path="/main/users" component={Users} />
</Switch>

Can I somehow omit adding /main before /main/users everytime I am in the Main component? Can /main be set to / within that component or do I have to explicitly type the full path every time?

I see discussions talking about something very similar (for example: Does react-router support relative links?) but is there anything for Router paths that can be configured? <Link to="users" /> is said to work but I can't get <Route path="users" /> to.

1 Answer 1

6

There is no "magic" in react-router that will automatically inject the current location, but you can do it pretty easily using this.props.location that is passed to the component from <Router />:

So if you are already at /main, you could set your paths to:

<Switch>
  <Route exact path={`${this.props.location.pathname}`} component={Dashboard} />
  <Route exact path={`${this.props.location.pathname}/users`} component={Users} />
</Switch>

Which would resolve as:

<Switch>
  <Route exact path="/main" component={Dashboard} />
  <Route exact path="/main/users" component={Users} />
</Switch>
Sign up to request clarification or add additional context in comments.

4 Comments

Is there any reason to access the current path as opposed to just hard-coding '/main/users'? Since you're in the Main component anyway?
@ShaunE.Tobias Accessing the current path instead of hard coding allows for easier code re-use for this component. If the path is hard coded and you change the app structure, you will most likely have to edit the paths. If it is always pulling the current path then you can rearrange the components without having to change any of the internals.
Fair point, thanks! I hadn't considered the path may be changed. I suppose in implementation you'd do some sort of risk assessment for that scenario since it would prevent future hassle, but could also be unnecessarily convoluted or expensive. Perhaps could be cleaned up by throwing the pathname into a const. Thanks again!
Note: This answer only applies to BrowserRouter and does not work when using HashRouter

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.