简体   繁体   中英

React Router first route with no menu or main layout

Im learning React and I came across with React Router. Ive done the basic routing tutorial already but I havent achieved my goal yet because Im lost.

I want to render my Login component firstly with no main navigation, just the pure Login, if succeeded then it will take to the main app with the main navigation (Links rendered).

I dont want the Login with any other routes showing up as links.

So, Ive tried to verify this in my componentDidMount, but I dont know if this redirect component works like that. If my Login component has the router then the other components will render below the login.

This is my Login component in a very basic way with bootstrap:

import React, { Component } from 'react';
// import { BrowserRouter as Router, Route, Redirect } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import logo from '../logo.svg';
import axios from 'axios';
// import TodosList from "./todos-list.component";

class Login extends Component{
    constructor(props){
        super(props);
        this.state = {
            email: '',
            password: ''
        }

    }

    componentDidMount() {
        const token = localStorage.getItem('token');
    }

    auth = (e) =>{
        e.preventDefault();
        axios.post('http://localhost:4000/api/login', {
            email: this.state.email,
            password: this.state.password
        })
            .then(response => {
                console.log(response.headers['x-auth-token']);
                if (response.headers['x-auth-token']){
                    localStorage.setItem('token', response.headers['x-auth-token']);
                }
            })
            .catch(error => {
                alert(`Usuario o Password Invalido`);
                this.setState({
                    email: '',
                    password: ''
                });
            });
    };

    onEmailChange = (e) =>{
        this.setState({
            email: e.target.value
        });
    };

    onPasswordChange = (e) =>{
        this.setState({
            password: e.target.value
        });
    };

    render(){
        return (
            <div className="container h-100">
                <div className="row h-100 justify-content-center align-items-center">
                    <form onSubmit={this.auth}>
                        <img src={logo} className="img-thumbnail"/>
                        <div className="form-group">
                            <label>Email</label>
                            <input value={this.state.email} onChange={this.onEmailChange} type="email"
                                   className="form-control" placeholder="Enter E-mail address"/>
                        </div>

                        <div className="form-group">
                            <label>Password</label>
                            <input value={this.state.password} onChange={this.onPasswordChange} type="password"
                                   className="form-control" placeholder="Enter Password"/>
                        </div>

                        <button type="submit" className="btn btn-primary col-sm-12">Login</button>
                    </form>
                </div>
            </div>
        );
    }
}

export default Login;

Just refresh my mind a bit please, Ive seen a lot of articles doing the main layout with links but at the beginning I want to show as a starting screen only my Login component without menu links on top. Then redirect to my main app with links if Login was succesful.

If you want to protect specific routes in your app then you should really do something like react training has with protected routes found here React Auth Workflow . But if you want to protect your entire app you can just do a simple if statement in you app's root. If there is no authentication return the login else return the app like so:

CodeSandbox Example

const App = () => {

  //Your authentication logic goes here or in a context component

  // If authentication is false then just return the login component
  if(!auth) return <Login/>

  // If authentication is successful then return the app
  return (
    <div className="App">
      <BrowserRouter>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/page">Page</Link>
          </li>
        </ul>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/page" component={Page} />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

This is obviously a simplified version of how to do this but I wanted it to be simple so you can see how its done easily. You should really store the auth token in a context store or something so you can use the token easily. Also if you want some public routes you should really study the link above to react training. But if you want to just protect the entire app then you can just do a simple if statement like above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM