Skip to content

Instantly share code, notes, and snippets.

@stackdumper
Created August 7, 2018 18:34
Show Gist options
  • Save stackdumper/5f1e5c4d16dd26d0edaad265bfddb761 to your computer and use it in GitHub Desktop.
Save stackdumper/5f1e5c4d16dd26d0edaad265bfddb761 to your computer and use it in GitHub Desktop.
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