5

I am new to React and React Router. I have been trying to create a single page application that has a layout with navigation bars and content and a login page that does not load inside this layout. I have been searching the web and stackoverflow, but have not been able to figure this out. To create my app, I used "yarn create react-app appName" and use "yarn add" to add react router. How do I need to create my routes such that I have a login page with its own layout and a main layout where my content can be displayed.

Here is my index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

Here is my App.js:

import React, { Component } from 'react';
import Main from "./Main";
import Login, {fakeAuth} from "./components/Login";
import {
    Route,
    NavLink,
    HashRouter,
    Redirect,
    withRouter,
    Switch,
    BrowserRouter
} from "react-router-dom";


class App extends Component {
  render() {
    return (
        <BrowserRouter>  
        <Switch>
          <Route exact path="/" component={Main} />  
          <Route path="/login" component={Login} /> 
        </Switch>
        </BrowserRouter>

    );
  }
}

export default App;

Here is my Login.js:

import React from 'react';
import {
    Route,
    NavLink,
    HashRouter,
    Redirect
} from "react-router-dom";

class Login extends React.Component {

    constructor() {

      super();

      this.state = {
        redirectToReferrer: false
      }
      this.login = this.login.bind(this);
    }

    login() {

      fakeAuth.authenticate(() => {
        this.setState({ redirectToReferrer: true })
      })
    }

    render() {
      const { from } = this.props.location.state || { from: { 
pathname: '/' } }
      const { redirectToReferrer } = this.state;

      if (redirectToReferrer) {
        return (
          <Redirect to={from} />
        )
      }

      return (
        <div>
          <p>You must log in to view the page at {from.pathname}</p>
          <button onClick={this.login}>Log in</button>
        </div>
      )
    }


  }

  /* A fake authentication function */

  export const fakeAuth = {
    isAuthenticated: false,
    authenticate(cb) {
      this.isAuthenticated = true;
      setTimeout(cb, 100);
    }
  };


  export default Login

Here is my Main.js:

import React, { Component } from 'react';
import Navigation from './components/Navigation'  
import LeftSidebar from './components/LeftSidebar';
import RightSidebar from './components/RightSidebar';
import Login, {fakeAuth} from "./components/Login";
import {
    Route,
    NavLink,
    HashRouter, 
    Redirect,
    withRouter,
    Switch
} from "react-router-dom";


/* Home component */
const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
)

/* Category component */
const Category = () => (
  <div>
    <h2>Category</h2>
  </div>
)

/* Products component */
const Products = () => (
  <div>
    <h2>Products</h2>
  </div>
)

class Main extends Component {
  render() {
    return (
        <HashRouter>
        <div className="container container-fluid">
            <Navigation/>
            <div className="row">
                <div className="col-md-3">
                    <LeftSidebar/>
                </div>

                <div className="col-md-6">
                  <Route exact path="/" component={Home} />
                  <Route path="/category" component={Category}/>
                  <PrivateRoute authed={fakeAuth.isAuthenticated} path='/products' component = {Products} />
                </div>

                <div className="col-md-3">
                    <RightSidebar/>
                </div>
            </div>
        </div>
        </HashRouter>
    );
  }
}

const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        fakeAuth.isAuthenticated === true ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{ pathname: "/login", state: { from: props.location } 
}}
          />
        )}
    />
  );
};

const AuthButton = withRouter(
  ({ history }) =>
    fakeAuth.isAuthenticated ? (
      <p>
        Welcome!{" "}
        <button
          onClick={() => {
            fakeAuth.signout(() => history.push("/"));
          }}
        >
          Sign out
        </button>
      </p>
    ) : (
      <p>You are not logged in.</p>
    )
);

export default Main;

My links to the routes are in my navigation component:

....
<ul>
    <li><Link to="/">Homes</Link></li>
    <li><Link to="/category">Category</Link></li>
    <li><Link to="/products">Products</Link></li>
</ul>
....

When I click the Home, Category, or Products link, I want the component to load in the SPA layout in Main.js and I want Login.js to load in its own page. Right now, Home, Category, Products, and Login are loading in the main layout. What do I need to change about these routes or other part of my code to get this working?

Edit:

Added my auth code in the Main.js class. Added Login.js class.

In addition to following some tutorials on this, I have been following the advice from this answer: Login Page Separated From Single-page Application (SPA) in ReactJS However, I am not quite getting it. I am not sure exactly what I need to add to make this work.

Here are images illustrating what I am trying to do:

Main.js: main SPA layout

Login.js: Login page

Current issue is login is loading in the main layout rather than its own page: Do NOT want this

Alice
  • 51
  • 6
  • Did you look at the [official example](https://reacttraining.com/react-router/web/example/auth-workflow)? It's explaining exactly what you're asking. The `PrivateRoute` in the example can be used to render all routes which should be private. – Marko Gresak May 24 '18 at 15:48
  • @MarkoGrešak I just looked at that example and tried formatting my code how it shows in the example. I am still getting issues though. Here the login component shows up inside my layout which I am not looking for. I believe it is because of the location of my tags, but I don't know what to change. I load a and then I have my tags because that is where my content needs to show up. When I have a tag the Login component loads where my content was rather than on a separate page. – Alice May 24 '18 at 16:20
  • did you ever figure this out i have the same problem – user210757 Sep 30 '19 at 20:05

0 Answers0