Created
August 7, 2018 18:34
-
-
Save stackdumper/5f1e5c4d16dd26d0edaad265bfddb761 to your computer and use it in GitHub Desktop.
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
import * as React from 'react' | |
import { Redirect } from 'react-router-dom' | |
import queryString from 'qs' | |
export const withRedirect = <P extends Object>( | |
reaction: (any) => boolean, | |
redirect: string | ((props: P) => string), | |
) => (WrappedComponent) => { | |
const WithRedirectWrapper = (props: P) => { | |
const condition = reaction(props) | |
if (!condition) { | |
return <WrappedComponent {...props} /> | |
} | |
const to: string = (typeof redirect === 'function') | |
? redirect(props) | |
: redirect | |
return <Redirect to={to} /> | |
} | |
return WithRedirectWrapper | |
} | |
export const withRedirectNextProvider = (route: string = '/') => (state) => { | |
const query = queryString.stringify({ | |
next: state.location.pathname, | |
}) | |
return `${route}?${query}` | |
} | |
export const withRedirectNextHandler = (defaultNext: string = '/') => (props) => { | |
const { '?next': next } = queryString.parse(props.location.search) | |
return next || defaultNext | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment