Skip to content

Instantly share code, notes, and snippets.

@ceuk
Last active July 17, 2018 21:04
Show Gist options
  • Save ceuk/43b729846f187bc6ecf71edac2160ecb to your computer and use it in GitHub Desktop.
Save ceuk/43b729846f187bc6ecf71edac2160ecb to your computer and use it in GitHub Desktop.
Sophie Help
import React, { Component } from 'react'
import { Route, withRouter, Redirect, BrowserRouter as Router } from 'react-router-dom'
import Login from 'some/path/Login'
// shitty 'homepage' component
const HomePage = () => (
<div>
Hello logged in person!! :)
</div>
)
class App extends Component {
//store auth status at the top level as we don't have redux
state = {
loggedIn: false,
loading: false,
authError: null
}
constructor(props){
super(props)
// check already auth'd and set state accordingly
}
// example login function
login = () => {
this.setState({loading: true})
myAuthLib.login()
.then(res => this.setState({loggedIn: true, loading: false}))
.catch(err => this.setState({authError: err, loading: false}))
}
render() {
const {loading, loggedIn, authError} = this.state
// super elegant loading screen
if (loading) {
return 'loading...'
}
// if not logged in (and not already on /login), redirect to /login
if (!loggedIn && this.props.location.pathname !== '/login') {
return (<Redirect
to={{
pathname: '/login',
//you would use this 'from' prop to redirect back after successful login
state: { from: this.props.location }
}}
/>)
}
// two situations where we'll see the main app:
// 1) we are authenticated (full access to all routes)
// 2) we are on /login
return (
<div>
<Route path="/" component={HomePage} />
// pass the auth state down into this component
<Route path="/login" render={(props) => <Login handleLogin={this.login} loggedIn={loggedIn} {...props} />} />
</div>
)
}
}
export default withRouter(App)
import ReactDOM from 'react-dom'
import App from 'some/path/App'
ReactDOM.render(
<Router>
<App />
</Router>
), document.getElementById('root'))
import React from 'react'
import { Redirect } from 'react-router-dom'
class Login extends React.Component {
render() {
const { from } = '/'
//this is set by our login function in the parent component
if (this.props.loggedIn) {
return <Redirect to={from && from.pathname ? from.pathname : '/'} />
}
return (
// call the parent login function on click
<button onClick={this.props.handleLogin}>Login</button>
)
}
}
export default Login
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment