import React, { Component } from "react"; import { BrowserRouter as Router, Route, Link, Redirect, withRouter } from "react-router-dom"; //////////////////////////////////////////////////////////// // 1. Click the public page // 2. Click the protected page // 3. Log in // 4. Click the back button, note the URL each time function AuthExample() { return (
  • Public Page
  • Protected Page
); } const fakeAuth = { isAuthenticated: false, authenticate(cb) { this.isAuthenticated = true; setTimeout(cb, 100); // fake async }, signout(cb) { this.isAuthenticated = false; setTimeout(cb, 100); } }; const AuthButton = withRouter( ({ history }) => fakeAuth.isAuthenticated ? (

Welcome!{" "}

) : (

You are not logged in.

) ); function PrivateRoute({ component: Component, ...rest }) { return ( fakeAuth.isAuthenticated ? ( ) : ( ) } /> ); } function Public() { return

Public

; } function Protected() { return

Protected

; } class Login extends Component { state = { redirectToReferrer: false }; login = () => { fakeAuth.authenticate(() => { this.setState({ redirectToReferrer: true }); }); }; render() { let { from } = this.props.location.state || { from: { pathname: "/" } }; let { redirectToReferrer } = this.state; if (redirectToReferrer) return ; return (

You must log in to view the page at {from.pathname}

); } } export default AuthExample;