Skip to content

Instantly share code, notes, and snippets.

@arasmussen
Created April 2, 2019 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arasmussen/f2c01dc858481590f6bffae6b540632c to your computer and use it in GitHub Desktop.
Save arasmussen/f2c01dc858481590f6bffae6b540632c to your computer and use it in GitHub Desktop.
External redirects for react-router 3.x
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 />
);
}
}
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) { ...
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