Skip to content

Instantly share code, notes, and snippets.

@wschenk
Created December 5, 2017 22:14
Show Gist options
  • Save wschenk/d80a1920eb043aa7717f731670d72605 to your computer and use it in GitHub Desktop.
Save wschenk/d80a1920eb043aa7717f731670d72605 to your computer and use it in GitHub Desktop.
Final App.js for authenticated route example
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
Switch
} from 'react-router-dom';
import AuthenticatedRoute from './authenticated_route';
const Nav = () => (
<ul>
<li><Link to='/'>Home</Link></li>
<li><Link to='/about'>About</Link></li>
<li><Link to='/session'>Session</Link></li>
<li><Link to='/secret'>Secret</Link></li>
</ul>
)
const Welcome = () => (
<div>
<h1>Welcome</h1>
<p>This is some text</p>
</div>
)
const About = () => (
<div>
<h1>About</h1>
<p>Sure, stuff</p>
</div>
)
const Secret = () => (
<div>
<h1>This is a secret</h1>
<p>Sorry, not everyone can see this</p>
</div>
)
const Session = ({authed,location,login}) => {
if( authed ) {
let l = location.location
let pathname = "/";
if( l && l.state && l.state.from ) {
pathname = l.state.from.pathname;
}
return <Redirect to={pathname}/>
} else {
return (
<div>
<button onClick={() => {login()}}>Click me</button>
</div>
)
}
}
class App extends Component {
state = {authed: false}
login = () => {this.setState( {authed: true} ) }
render() {
return (
<Router>
<div>
<Nav/>
{ this.state.authed && <p>Logged in</p>}
<Switch>
<AuthenticatedRoute authed={this.state.authed} path="/secret" component={Secret}/>
<Route path="/about" component={About}/>
<Route path="/session" render={(location) => <Session location={location} login={this.login} authed={this.state.authed}/> }/> } />
<Route component={Welcome}/>
</Switch>
</div>
</Router>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment