Last active
September 15, 2015 03:41
-
-
Save insin/baf0136e51b03819f3ac to your computer and use it in GitHub Desktop.
Programmatic redirect for React Router 1.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var { formatPattern } = require('react-router/lib/URLUtils'); | |
/** | |
* Programatic equivalent of what's done with a JSX <Redirect/>, as of 6264a91. | |
* | |
* See: | |
* 1. https://github.com/rackt/react-router/blob/6264a91e6f037c3798553cd04ce9c0118f07c9ff/modules/RouteUtils.js#L63 | |
* 2. https://github.com/rackt/react-router/blob/6264a91e6f037c3798553cd04ce9c0118f07c9ff/modules/Redirect.js#L13%29 | |
* 3. https://github.com/rackt/react-router/blob/6264a91e6f037c3798553cd04ce9c0118f07c9ff/modules/RouteUtils.js#L25 | |
* | |
* Usage: redirect({from: '/', to: '/index'}) | |
*/ | |
function redirect(options) { | |
var route = Object.assign({}, options); | |
if (route.from) | |
route.path = route.from; | |
route.onEnter = function(nextState, transition) { | |
var { location, params } = nextState; | |
var pathname = route.to ? formatPattern(route.to, params) : location.pathname; | |
transition.to( | |
pathname, | |
route.query || location.query, | |
route.state || location.state | |
); | |
}; | |
return route; | |
} | |
module.exports = redirect; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey mate,
Was looking at a solution like that for redirections in my app with React Router 1.0. But then I noticed that the History API is available and allows you to redirect, even with classes, very easily:
https://github.com/rackt/react-router/blob/master/docs/api/History.md
However, I didn't really understand how transition.to is working since you do not provide a Route object but a simple string as input param.