Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create alias routes using react router?

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)?

like image 342
Santosh Kewat Avatar asked Apr 19 '17 10:04

Santosh Kewat


People also ask

Is it possible to configure routes programmatically in react?

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 .

How do I create a private route in react?

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.

What is the best way to redirect a page using react router?

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.


2 Answers

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!

like image 175
socket_var Avatar answered Oct 23 '22 16:10

socket_var


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" />
like image 32
Bartek Fryzowicz Avatar answered Oct 23 '22 16:10

Bartek Fryzowicz