Created
April 7, 2017 19:41
-
-
Save bcavileer/d583b61ae18389349d53304b039c7caa to your computer and use it in GitHub Desktop.
Composing login required behavior on child routes
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
| // 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