use-named-routes
use-named-routes copied to clipboard
Redirect and IndexRedirect Behavior
Hi,
I'm trying to get redirects to work with the history used by use-named-routes. I've build a minimal viable example (MVE) in React and React-Router without use-named-routes. The goal is for the root path and the widget-2 path to always redirect to widget-1.
import React from 'react';
import { render } from 'react-dom';
import {
browserHistory, IndexRedirect, Link, Redirect, Route, Router,
} from 'react-router';
const Widget = () => {
return (
<Link to="widget-2">
This is a loop!
</Link>
);
};
const AppRoutes = () => {
return (
<Router history={browserHistory} >
<Route path="/" >
<IndexRedirect to="widget-1" />
<Route path="widget-1" component={Widget} />
<Redirect from="widget-2" to="widget-1" />
</Route>
</Router>
);
};
render(<AppRoutes />, document.querySelector('#react_app'));
The code above works exactly as desired.
With use-named-routes, both the IndexRedirect and the Redirect behaviors appear to stop working. While the Widget component is still displayed in the browser, the URL path is never updated.
import createHistory from 'history/lib/createBrowserHistory';
import React from 'react';
import { render } from 'react-dom';
import {
IndexRedirect, Link, Redirect, Route, Router, useRouterHistory,
} from 'react-router';
import useNamedRoutes from 'use-named-routes';
const Widget = () => {
return (
<Link to="/widget-2">
This is a widget loop!
</Link>
);
};
const AppRoutes = (
<Route path="/" >
<IndexRedirect to="widget-1" />
<Route name="widgetOne" path="widget-1" component={Widget} />
<Redirect from="widget-2" to="widget-1" />
</Route>
);
const history = (
useNamedRoutes(useRouterHistory(createHistory))({ routes: AppRoutes })
);
render(
<Router history={history} routes={AppRoutes} />,
document.querySelector('#react_app')
);
You'll note that the MVE above does not use any names in the redirect components. Setting the to attribute/argument on IndexRedirect or Redirect to widgetOne (the name of the Route) results in an error stating that Location "/widgetOne" did not match any routes.
I believe this is a bug, but I apologize if the error is in my code.
Interesting.
Your redirects above should be written as /widget-1 if you want them to be paths.
If you want to use redirects to names, you'll need to directly call replace in onEnter, because of the logic in <Redirect> for handling relative redirects not playing well with the named routes support here.
I suppose I'll have to document this better.
Thanks for the quick response!
The problem I was trying to highlight was the fact that redirects no longer update the URL path in the browser with use-named-routes.
I'm happy to help with documentation, and may have a crack at that tomorrow.
It's not redirects per se – just the <Redirect> component.