Skip to content

Instantly share code, notes, and snippets.

@buster95
Created November 17, 2020 20:10
Show Gist options
  • Save buster95/8b9b2b6edf5cf9102f91c20595434930 to your computer and use it in GitHub Desktop.
Save buster95/8b9b2b6edf5cf9102f91c20595434930 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