title: Redirect to login page when token is invalid on React
body: <p>I have seen multiple threads that suggest the use of Routes on redux, but in general, the examples contain a public Main Page with the options to Log in, Logout, Access to Dashboard, etc.
  What I'm looking for is to allow the user to access the app if the token is still valid, otherwise, it should redirect to the Login page, which is not part of the main layout of the app.
  Let me show some code:</p>
  <pre><code>function checkAuth() {
        const token = localStorage.getItem('token');
        if (!token) {
          return false;
        }
  
        try {
          let payload = decode(token);
          if (payload.exp &lt; new Date().getTime() / 1000) {
            return false;
          }
        } catch (e) {
          return false;
        }
        return true;
      }
  
      class Main extends Component {
        constructor(props) {
          super(props);
          this.output = this.output.bind(this)
          this.state = { loggedin: false }
        }
        output(evt) {
            this.setState({loggedin: evt})
        }
        Content({output, loggedin})
        {
          if (checkAuth())
            return(&lt;Layout/&gt;);
          if (!loggedin)
            return(&lt;Login func={output}/&gt;);
          else
            return(&lt;Layout/&gt;);
        }
        render() {
          return (
              &lt;this.Content output={this.output} loggedin={this.state.loggedin}/&gt;
           )
        };
      }
  </code></pre>
  <p>First, I made validation of the token; if it is still valid, the function &quot;  Content&quot; will return the Dashboard, otherwise, it will return the Login Page. Then, I send a function &quot;output&quot; to the child component &quot;Login&quot;, so the Login page is able to change the state of the flag &quot;loggedin&quot;, the change of this state will render the dashboard.</p>
  <p>My App component:</p>
  <pre><code>class App extends Component {
    render() {
      return (
        &lt;div className=&quot;App&quot;&gt;
            &lt;Router&gt;
              &lt;Route path=&quot;/&quot; component={Main} /&gt;
            &lt;/Router&gt;
        &lt;/div&gt;
       )
    };
  }
  </code></pre>
  <p>It works by now as expected, but I have the feeling the code logic can be improved. It would be helpful for some opinions about it, I'm a React beginner.
  I have published the code on Github: <a href="https://github.com/shernandezp/react_basic_layout/" rel="nofollow noreferrer">Full Code</a></p>