I am working on a new project to be built using react and react-router. I am planning to restructure my routes in such a way that it is cleaner than before. However, I don't want to break older bookmarks that users may have.
For instance, my new routes might look like:
<Route path="/" component={Layout}>
<Route component={ItemList} path="items/:category" />
<Route component={ItemDetail} path="item/:designCode" />
</Route>
Some example routes could be, say - /items/electronics, /items/gifts.
However, I have a legacy code base that had routes of the kind - /electronic-items, /buy-gifts, etc.
Is there a way I can create route aliases to be able to map these legacy URLs to the newly structured ones?
I have come across something similar in Vue 2.0, but am particularly interested in a react solution. Any suggestions (apart from - use redirects or use Vue itself instead :D)?
With v4 of React Router, there are three approaches that you can take to programmatic routing within components. Use the withRouter higher-order component. Use the context .
Path: /src/_components/PrivateRoute.jsx The react private route component renders child components ( children ) if the user is logged in. If not logged in the user is redirected to the /login page with the return url passed in the location state property.
The useHistory() hook is first imported and then assigned to a variable, which is subsequently utilized in a button (for example) to redirect users once a specific action is taken. Using the onClick event, we can then call the . push() method to tell React Router where we want the button to redirect to.
I am using react-router-dom v4.3.1 and as of this version multiple paths can be provided as an array to the path prop on the Route component like:
<Route path={["oldListUrl", "newListUrl"]} component={ItemList}/>
I believe this is much better than redirects. Hope this helps!
Assuming that you're using React-Router v4
you can use Redirect
component like this:
<Route path="newListUrl" component={ItemList}/>
<Route path='/oldListUrl' render={() => (
<Redirect to="newUrl" />
)}/>
If you're using React-Router v3
:
<Route path="newListUrl" component={ItemList}/>
<Redirect from='oldListUrl'to="newListUrl" />
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