Redirection after login in REACT JS

1

I'm doing a project in React where I have a Login form that makes a search to a Rest API, and that after that, it should go to a new page where there will be a menu. I have managed to make the query to the API, but I can not get the redirection to take place, the most I have done is to render the new component in the root, but I think that is not the most correct way. I attach my code:

Index.js:

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

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

Index.js brings up the App.js screen, which contains the login form and the authentication method:

App.js:

//Dependencies
import React, { Component } from 'react';
import './Global/css/App.css';
import ReactDOM from 'react-dom';

//Sources
import PanelUsuario from './PanelUsuario/PanelUsuario';

//Data
import conexion from '../data/conexion';
import items from '../data/menu';
import { BrowserRouter as Router } from 'react-router-dom'; 

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: ''};
  }

  handleUsername (e){
        this.setState({username: e.target.value});
  }

  handlePassword (e){
        this.setState({password: e.target.value});
  }  

  login (e){
        e.preventDefault();

        const username = this.state.username;
        const password = this.state.password;
        let urlEnvio="LLAMADA A LA API Rest";

        fetch (urlEnvio, {
          method: 'GET'
        })
        .then(res => res.json())
          .then(res => {
            if(res.count === 0){
              ReactDOM.render(
              <div className="alert alert-danger" id='UserNotExist'>
                El usuario introducido no existe.
              </div>,
              document.getElementById('info')
            );  
            }else{
              ReactDOM.render(
              <Router>  
                <PanelUsuario title='Pedidos' items={items}/>
              </Router>,
                document.getElementById('root')
              );

            }      
        });
    }



  render() {
    return (
     <div className="container-fluid">
       <div className="row">
         <div className="col-md-12" id="capaForm">
           <div className="row">
             <div className="col-md-4">
             </div>
             <div className="col-md-4">
               <form>
                 <div className="form-group">
                   <label>Usuario</label>
                   <input type="text" 
                       className="form-control"
                       id="nameUser" 
                       value={this.state.username}
                       onChange={this.handleUsername.bind(this)}/>
                 </div>
                 <div className="form-group"> 
                   <label>Contraseña</label>
                   <input type="password"
                       className="form-control"
                       id="passwordUser"
                       value={this.state.password}
                       onChange={this.handlePassword.bind(this)}/>
                 </div>
                 <button className="btn btn-default" 
                     id="btnLogin"
                     onClick={this.login.bind(this)}>
                   Iniciar Sesión
                 </button>
               </form>
               <div id='info'></div>
             </div>
             <div className="col-md-4"></div>
           </div>
         </div>
       </div>
     </div>
    );
  }
}

export default App;

This loads me the user panel, which contains a menu:

PanelUsuario.js:

//Dependencias
import React, { Component } from 'react';
import PropTypes from 'prop-types';

//Assets


import {Link} from 'react-router-dom';


class PanelUsuario extends Component {

    static propTypes = {
        title: PropTypes.string.isRequired,
    items: PropTypes.array.isRequired
  };    

  render() {
    const {items} = this.props;

    return (
      <div className="container-fluid">
        <div className="row">
          <div className="col-md-12" id="capaForm">             
            <nav className="navbar navbar-default navbar-fixed-top">
              <div className="navbar-header">
                <button type="button" className="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                  <span className="sr-only">Toggle navigation</span><span className="icon-bar"></span><span className="icon-bar"></span><span className="icon-bar"></span>
                </button>
                <a className="navbar-brand">Brand</a>
              </div>
              <div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul className="nav navbar-nav">
                  {items && items.map(
                    (item, key) => <li key={key}><Link to={item.url}>{item.title}</Link></li>)}
                </ul>
              </div>
            </nav>          
          </div>
        </div>
      </div>    
    );
  }
}

export default PanelUsuario;

On this page the menu is filled with the data that is stored in a separate file:

Menu.js:

export default [
    {
        title : "Opcion1",
        url : "/Opcion1"
    },
    {
        title : "Opcion2",
        url : "/Opcion2"
    },
    {
        title : "Opcion3",
        url : "/Opcion3"
    }
];

And finally, a file where I have stored the function responsible for routing:

route.js:

import React from 'react';
import { Route, Switch } from 'react-router-dom';


//Components
import App from './App';
import opcion1 from './Opcion1';
import opcion2 from './Opcion2';
import opcion3 from './Opcion3';
import Pagina404 from './Pagina404/Pagina404';



const AppRoutes = () =>

<App>
    <Switch>
        <Route exact path="/Opcion1" component = {Opcion1} />
        <Route exact path="/Opcion2" component = {Opcion2} />
        <Route exact path="/Opcion3" component = {Opcion3} />
        <Route component={Pagina404} />
    </Switch>
</App>;

export default AppRoutes;

I would appreciate someone to guide me in this matter because I find myself quite confused. Thank you very much.

    
asked by AntonioMP87 28.08.2017 в 16:36
source

1 answer

1

You can try to replace:

      ReactDOM.render(
      <Router>  
        <PanelUsuario title='Pedidos' items={items}/>
      </Router>,
        document.getElementById('root')
      );

by:

     ReactDOM.render(
         <Redirect to='/Option1'/>
     );
    
answered by 31.08.2017 в 17:03