Skip to content

Instantly share code, notes, and snippets.

@oojikoo
Created July 17, 2018 23:29
Show Gist options
  • Select an option

  • Save oojikoo/f22bad3f376235b88467255522d8e0ed to your computer and use it in GitHub Desktop.

Select an option

Save oojikoo/f22bad3f376235b88467255522d8e0ed to your computer and use it in GitHub Desktop.
Conditional Route for react-router. tags: #react #react-router

Conditional Route

Check first something before rendering it.

Usage

<RouteIf
  condition={(() => {
    return true
  })()}
  privateRoute={true}
  path="/path/:value"
  component={MyComponent}
/>
import React from 'react'
import {
Route,
Redirect
} from 'react-router-dom'
class PrivateRoute extends React.Component {
render() {
const { component: Component, ...rest } = this.props
return (
<Route {...rest} render={(props) => {
return true ? (
<Component {...props} />
):(
<Redirect to={{
pathname: '/login',
state: { from: this.props.location }
}} />
)
}
} />
)
}
}
export default PrivateRoute
import React from 'react'
import {
Route,
Redirect,
} from 'react-router-dom'
import PrivateRoute from '~/routes/Private'
const RouteIf = ({ condition, privateRoute, path, component }) => {
return condition ? (
privateRoute ?
<PrivateRoute path={path} component={component} /> :
<Route path={path} component={component} />
):(
<Redirect to="/" />
)
}
export default RouteIf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment