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.
This is a quick example of how to navigate up levels with relative links using the React Router <Link> component. The solution is to use the following react router <Link> tags to link up one or two levels. Note: Linking up to relative paths like this leaves trailing slash on the end of the destination URL.
Follow the steps given below to install Router in your React application: Step 1: cd into your project directory i.e geeks. After installing react-router-dom, add its components to your React application. Adding React Router Components: The main Components of React Router are:
Create React App doesn't include page routing. React Router is the most popular solution. To add React Router in your application, run this in the terminal from the root directory of the application: Note: This tutorial uses React Router v6. If you are upgrading from v5, you will need to use the @latest flag:
Routes: To render a single component, wrap all the routes inside the Routes Component. Switch groups together several routes, iterates over them and finds the first one that matches the path. Thereby, the corresponding component to the path is rendered. Now, we you can click on the links and navigate to different components.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With