router.jsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import React, { Component } from "react";
  2. import {
  3. BrowserRouter as Router,
  4. Route,
  5. Link,
  6. Redirect,
  7. withRouter
  8. } from "react-router-dom";
  9. ////////////////////////////////////////////////////////////
  10. // 1. Click the public page
  11. // 2. Click the protected page
  12. // 3. Log in
  13. // 4. Click the back button, note the URL each time
  14. function AuthExample() {
  15. return (
  16. <Router>
  17. <div>
  18. <AuthButton />
  19. <ul>
  20. <li>
  21. <Link to="/public">Public Page</Link>
  22. </li>
  23. <li>
  24. <Link to="/protected">Protected Page</Link>
  25. </li>
  26. </ul>
  27. <Route path="/public" component={Public} />
  28. <Route path="/login" component={Login} />
  29. <PrivateRoute path="/protected" component={Protected} />
  30. </div>
  31. </Router>
  32. );
  33. }
  34. const fakeAuth = {
  35. isAuthenticated: false,
  36. authenticate(cb) {
  37. this.isAuthenticated = true;
  38. setTimeout(cb, 100); // fake async
  39. },
  40. signout(cb) {
  41. this.isAuthenticated = false;
  42. setTimeout(cb, 100);
  43. }
  44. };
  45. const AuthButton = withRouter(
  46. ({ history }) =>
  47. fakeAuth.isAuthenticated ? (
  48. <p>
  49. Welcome!{" "}
  50. <button
  51. onClick={() => {
  52. fakeAuth.signout(() => history.push("/"));
  53. }}
  54. >
  55. Sign out
  56. </button>
  57. </p>
  58. ) : (
  59. <p>You are not logged in.</p>
  60. )
  61. );
  62. function PrivateRoute({ component: Component, ...rest }) {
  63. return (
  64. <Route
  65. {...rest}
  66. render={props =>
  67. fakeAuth.isAuthenticated ? (
  68. <Component {...props} />
  69. ) : (
  70. <Redirect
  71. to={{
  72. pathname: "/login",
  73. state: { from: props.location }
  74. }}
  75. />
  76. )
  77. }
  78. />
  79. );
  80. }
  81. function Public() {
  82. return <h3>Public</h3>;
  83. }
  84. function Protected() {
  85. return <h3>Protected</h3>;
  86. }
  87. class Login extends Component {
  88. state = { redirectToReferrer: false };
  89. login = () => {
  90. fakeAuth.authenticate(() => {
  91. this.setState({ redirectToReferrer: true });
  92. });
  93. };
  94. render() {
  95. let { from } = this.props.location.state || { from: { pathname: "/" } };
  96. let { redirectToReferrer } = this.state;
  97. if (redirectToReferrer) return <Redirect to={from} />;
  98. return (
  99. <div>
  100. <p>You must log in to view the page at {from.pathname}</p>
  101. <button onClick={this.login}>Log in</button>
  102. </div>
  103. );
  104. }
  105. }
  106. export default AuthExample;