0

Apologies if it sounds stupid question. I'm trying to redirect user to the content pages of the app when they are signed in. My current implementation correctly changes the URL in the address bar but doesn't render a component and shows a blank page. Is there something i'm missing in here. Could you please suggest what am i'm missing ?

I tried googling it but couldn't make it work. Here are some of the links i tried.

1- https://tylermcginnis.com/react-router-programmatically-navigate/

2- https://learnwithparam.com/blog/redirect-route-in-react-router/

3- Programmatically navigate using react router

Login Component

class Login extends React.Component {
    handleSubmit(e) {
        e.preventDefault();
        var value = true;
        localStorage.setItem('userLoggedIn', JSON.stringify(value));

        this.setState({
            toUsers: true
        })

        //this.props.history.push('/users')
    }

    render() {
        if (this.state.toUsers === true) {
            return <Redirect to="/users" />
        }

        return (
            <div className="Login">
                <form onSubmit={this.handleSubmit}>
                    Email
                    <input
                        type="text"
                        value={this.state.email}
                        onChange={this.handleEmailChange}
                    />
                    Password
                    <input
                        type="text"
                        value={this.state.password}
                        onChange={this.handlePasswordChange}
                    />
                    <button>
                        Login
                    </button>
                </form>
            </div>
        );
    }
}

export default Login;

App component:

import React, { Component } from 'react';
import { BrowserRouter, HashRouter, Switch, Route } from 'react-router-dom';
import Navigation from './common/Navigation';
import Users from './users/Users.jsx';
import Roles from './roles/Roles.jsx';
import ProtectedRoute from './authentication/ProtectedRoute.jsx';


export default class App extends Component {
  constructor(props) {
    super(props);
  }

  render() {  
    return <Navigation>
      <Switch>
        <Route exact path="/users" component={Users} />
        <Route exact path="/roles" component={Roles} />
        <Route render={() => <div>Not Found</div>} />
      </Switch>
    </Navigation>
  }
}

Component which decides if login page should be displayed or the content pages of the application

export default class AppAuthenticated extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            email: "",
            password: "",
            toUsers: false,
            isUserLoggedIn: false
        };
    }

    componentDidMount() {
        const isUserLoggedIn = JSON.parse(localStorage.getItem('userLoggedIn'));
        this.setState({
            isUserLoggedIn: isUserLoggedIn
        });
    }

    render() {
        return (
            <>
                {this.state.isUserLoggedIn ? (
                    <App />
                ) : (
                        <Login />
                    )}
            </>
        );
    }
}

Main App Component which renders the app

import React from 'react'
import ReactDOM from "react-dom";
import App from './pages/App'
import { BrowserRouter, HashRouter, Switch, Route } from 'react-router-dom';
import PropTypes from "prop-types";
import { withRouter } from "react-router";
import Login from './pages/authentication/Login.jsx';
import AppAuthenticated from './pages/authentication/AppAuthenticated.jsx';

ReactDOM.render(
    <HashRouter>
        <AppAuthenticated />
    </HashRouter>,
    document.getElementById("root")
);

Expected Behavior: When user is signed in successfully, they should be redirected to the "App" component where I've defined all the routes that logged in user can access

  • add more code of app.js component – Kishan Jaiswal Oct 01 '19 at 04:57
  • 1
    Easy solution is just refresh the page after login or change state of `this.state.isUserLoggedIn` to true and try Redirect. That will work. Redirect is not working now because < App> is not render before you are login as this.state.isUserLoggedIn is false by default and is not updated after login. – Kais Oct 01 '19 at 04:58
  • @KishanJaiswal I've updated the app.js code and the component code which renders the app with HashRouter – learner_2020 Oct 01 '19 at 05:04
  • just pass on function as props to login component and when login is done call the function and change state value of (isUserLoggedIn) to true – Kishan Jaiswal Oct 01 '19 at 05:08
  • @kais Thanks for your solution specially "refreshing" the page – learner_2020 Oct 02 '19 at 04:09

2 Answers2

0

In your app.js, pass a prop to your login component that can change the container state to render your content pages.

setLoggedIn = ()=>{
    this.setState({isUserLoggedIn: true});
}

render() {
    return (
            <>
            {this.state.isUserLoggedIn ? (
                <App />
            ) : (
                <Login loginSuccess={this.setLoggedIn} />
                )}
        </>
    );
}

Then in your Login Component...

handleSubmit(e) {
    e.preventDefault();
    var value = true;
    localStorage.setItem('userLoggedIn', JSON.stringify(value));

    this.setState({
        toUsers: true
    })
    this.props.loginSuccess();
    //this.props.history.push('/users')
}
Maddy Blacklisted
  • 1,190
  • 1
  • 7
  • 17
-1
setLoggedIn = ()=>{
  this.setState({isUserLoggedIn: true});
}

render() {
   return (
         <>
          {this.state.isUserLoggedIn ? (
            <App />
        ) : (
            <Login loginSuccess={this.setLoggedIn} />
            )}
    </>
  );
}

this is missing in your passing props @maddy

Kishan Jaiswal
  • 644
  • 3
  • 14