Skip to content

Instantly share code, notes, and snippets.

@bcavileer
Created April 7, 2017 19:41
Show Gist options
  • Select an option

  • Save bcavileer/d583b61ae18389349d53304b039c7caa to your computer and use it in GitHub Desktop.

Select an option

Save bcavileer/d583b61ae18389349d53304b039c7caa to your computer and use it in GitHub Desktop.
Composing login required behavior on child routes
// Not working due to <Switch>?
class LoginRequired extends React.Component {
componentWillMount() {
let children = this.props.children;
if (!this.props.loggedIn) {
children = this.props.children.map((child, index) => {
const redirectProps = { render: () => (<Redirect to="/" />), key: index }
const propsWithRedirect = Object.assign(redirectProps, child.props)
propsWithRedirect.component = undefined
return React.cloneElement(child, propsWithRedirect)
})
}
this.children = children;
}
render() {
return (<div>{this.children}</div>)
}
}
class App extends React.Component {
state = {
loggedIn: false
}
toggleLogin = () => {
this.setState({ loggedIn: !this.state.loggedIn })
}
render() {
return (
<div>
<h1>People Viewer</h1>
<button onClick={this.toggleLogin}>{this.state.loggedIn ? 'Logout' : 'Login'}</button>
<Router>
<Switch>
<Route exact path="/" component={Home} />
<LoginRequired loggedIn={this.state.loggedIn}>
<Route path="/profile/:userId" component={Profile} />
<Route path="/users/:userId" render={({ match }) => (
<Redirect to={`/profile/${match.params.userId}`} />
)} />
</LoginRequired>
<Route component={NoMatch} />
</Switch>
</Router>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment