react-router-dispatcher action for redirects
MIT License
A react-router-dispatcher action for defining react-router redirects that support server-side streaming.
Read the react-router-dispatcher documentation if you haven't already done so.
There is an working example here that incorporates redirects and metadata
npm install --save react-router-dispatcher-redirect
yarn add react-router-dispatcher-redirect
import redirectAction, { redirectRoute, REDIRECT, STATUS_CODE } from 'react-router-dispatcher-redirect';
// REDIRECT is the action name, used to configure react-router-dispatcher
redirectRoute()
and withRedirect()
// routes.js
import { redirectRoute, withRedirect } from 'react-router-dispatcher-redirect';
import { Root, Home, MyAccount } from './components';
const routes = [
{ component: Root,
routes: [
{ path: '/',
exact: true,
component: Home
},
{ path: '/myaccount',
exact: true,
component: withRedirect({
to: '/login',
shouldRedirect: (routeProps, props) => true, // conditional redirect
mapParamsToProps: p => p
})(MyAccount)
},
// redirect routes
redirectRoute({ from: '/hello', to: '/world' }),
redirectRoute({ from: '/temporary', to: '/login', statusCode: 302 })
]
}
]
export default routes;
import { createRouteDispatchers } from 'react-router-dispatcher';
import { STATUS_CODE, REDIRECT } from 'react-router-dispatcher-redirect';
import routes from './routes';
const {
UniversalRouteDispatcher,
ClientRouteDispatcher,
dispatchClientActions,
dispatchServerActions
} = createRouteDispatchers(routes, [[STATUS_CODE, REDIRECT]]);
// Server dispatch
dispatchServerActions(req.url, params).then(({ httpResponse: { statusCode, redirect } }) => {
if (redirect) {
// redirect the response - expressjs syntax
return res.redirect(statusCode, redirect);
}
res.status(statusCode);
// render the application
});
redirectAction(props: Object)
mapParamsToProps: (params: Object, routerCtx: Object) => Object
statusCode: number
shouldRedirect: boolean | (routeProps: Object, componentProps: Object) => boolean
push: boolean
redirectRoute(props: Object)
define a react-router-config redirect route
from: string
to: string | object
statusCode: number
push: boolean
strict: boolean
from
path use a strict matchexact: boolean
from
path use an exact matchwithRedirect(props: Object)
Used to enable conditional redirects, for example protecting authenticated routes
to: string | object
mapParamsToProps: (params: Object, routerCtx: Object) => Object
shouldRedirect: boolean | (props: Object) => boolean
statusCode: number
push: boolean
strict: boolean
from
path use a strict matchexact: boolean
from
path use an exact matchFor questions or issues, please open an issue, and you're welcome to submit a PR for bug fixes and feature requests.
Before submitting a PR, ensure you run npm test
to verify that your coe adheres to the configured lint rules and passes all tests. Be sure to include unit tests for any code changes or additions.
MIT