Created
April 2, 2019 19:42
-
-
Save arasmussen/f2c01dc858481590f6bffae6b540632c to your computer and use it in GitHub Desktop.
External redirects for react-router 3.x
This file contains 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
import React, { Component, PropTypes } from 'react'; | |
// This file is heavily based on: | |
// https://github.com/ReactTraining/react-router/blob/v3/modules/Redirect.js | |
export default class ExternalRedirect extends Component { | |
static propTypes = { | |
from: PropTypes.string.isRequired, | |
to: PropTypes.string.isRequired, | |
}; | |
static createRouteFromReactElement = (element) => { | |
const { type } = element; | |
const route = Object.assign({}, type.defaultProps, element.props); | |
route.childRoutes = []; | |
delete route.children; | |
if (route.from) route.path = route.from; | |
route.onEnter = function (nextState, replace) { | |
const location = nextState.location; | |
if (typeof window !== 'undefined') { | |
window.location = route.to; | |
return; | |
} | |
replace({ | |
pathname: location.pathname, | |
query: location.query, | |
state: { | |
externalURL: route.to, | |
}, | |
}); | |
}; | |
return route; | |
}; | |
static getRoutePattern = (routes, routeIndex) => { | |
let parentPattern = ''; | |
for (var i = routeIndex; i >= 0; i--) { | |
const route = routes[i]; | |
const pattern = route.path || ''; | |
parentPattern = pattern.replace(/\/*$/, '/') + parentPattern; | |
if (pattern.indexOf('/') === 0) break; | |
} | |
return '/' + parentPattern; | |
}; | |
render() { | |
return ( | |
<div /> | |
); | |
} | |
} |
This file contains 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
match({ | |
history, | |
routes, | |
location: request.url, | |
}, (error, redirectLocation, renderProps) => { | |
if (redirectLocation) { | |
const { | |
pathname, | |
search, | |
state, | |
} = redirectLocation; | |
const location = state && state.externalURL || (pathname + search); | |
response.writeHead(302, { | |
Location: location, | |
}); | |
response.end(); | |
} else if (renderProps) { ... |
This file contains 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
export default ( | |
<Route> | |
<Route path="/some/path" component={SomeComponent} /> | |
<ExternalRedirect from="/foo/bar" to="https://canny.io" /> | |
</Route> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment