Forked from ryanflorence/auth-with-reach-router.jsx
Created
November 8, 2018 06:00
-
-
Save tolotrasmile/4798ebcf3d6cb0050f885cc339919816 to your computer and use it in GitHub Desktop.
This file contains 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
let UserContext = React.createContext(); | |
class App extends React.Component { | |
state = { | |
user: null, | |
setUser: user => { | |
this.setState({ user }); | |
} | |
}; | |
render() { | |
return ( | |
<UserContext.Provider value={this.state}> | |
<Router> | |
<Home path="/" /> | |
<About path="/about" /> | |
<PrivateRoute as={Dashboard} path="/dashboard" /> | |
</Router> | |
</UserContext.Provider> | |
); | |
} | |
} | |
class PrivateRoute extends React.Component { | |
static contextType = UserContext; | |
render() { | |
let { as: Comp, ...props } = this.props; | |
return this.context.user ? <Comp {...props} /> : <Login />; | |
} | |
} | |
class Login extends React.Component { | |
static contextType = UserContext; | |
render() { | |
return ( | |
<form | |
onSubmit={async () => { | |
let user = await doWhateverYouNeedToDoToLogin(); | |
this.context.setUser(user); | |
}} | |
/> | |
); | |
} | |
} | |
function Home() { | |
return <div>home</div>; | |
} | |
function About() { | |
return <div>about</div>; | |
} | |
function Dashboard() { | |
return <div>Protected dashboard</div>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment