Redirect doesn't redirect to components

20,466

Solution 1

In your case this.props.router would be undefined. Here's a rough solution that I made. Reading the comments in the code will help.

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom'; // add this import 
export default class Login extends Component {
constructor (props){
        super(props);
        this.state = {
            email : '',
            password : '',
            userId : '',
            redirectToReferrer: true // when you're checking if the user is authenticated you have to keep this false
        };
    }
 //    componentWillReceiveProps(nextProps) {
 //    if ( put your authentication logic here ) {
    //       this.setState({ redirectToReferrer: true });
    //     }
    // }
    login(){
      this.props.history.push('/dashboard');
    }
 render() {
    const from = { pathname: '/dashboard' };
    const { redirectToReferrer } = this.state; // redirectToReferrer is true in the initial state
    if (redirectToReferrer) { // if true the user will be redirected to /dashboard
      return <Redirect to={from} />;
    }
    return (
    <div className="container-fluid">
    <div className="row">
        <div className="col-xl-12">    
            <div className="login-page-block-inner">
                <div className="login-page-block-form">
                        <div className="form-actions">
                            <button type="button"  className="btn btn-primary width-150" onClick={(e) => { this.login()} }>Sign In</button>
                        </div>                       
                </div>
            </div>
        </div>
    </div>
</div>
    );
  }
}

Solution 2

In React 16 and above you can use Redirect from 'react-router-dom'

import  { Redirect } from 'react-router-dom' 

Define state in your component

this.state = {
  loginStatus:true
}

than in your render method

render () {
if(this.state.loginStatus){
    return <Redirect to='/home'  />
 }
return(
 <div> Please Login </div>
 )
}

Solution 3

Make use of withRouter frun react-router to inject router as a prop to your login component

import React, { Component } from 'react';
import {withRouter} from 'react-router'
import $ from 'jquery';
class Login extends Component {
constructor (props){
        super(props);
        this.state = {
            email : '',
            password : '',
            userId : ''
        };
    }
    login(){
      this.props.history.push('/dashboard');
    }
 render() {
    return (
    <div className="container-fluid">
    <div className="row">
        <div className="col-xl-12">    
            <div className="login-page-block-inner">
                <div className="login-page-block-form">
                        <div className="form-actions">
                            <button type="button"  className="btn btn-primary width-150" onClick={(e) => { this.login()} }>Sign In</button>
                        </div>                       
                </div>
            </div>
        </div>
    </div>
</div>
    );
  }
}
export default withRouter(Login)
Share:
20,466

Related videos on Youtube

Author by

Eswaran Arumugam

Updated on May 21, 2022

Comments

  • Eswaran Arumugam about 13 hours

    This is my index.js page

    import React from 'react';
    import ReactDOM from 'react-dom';
    import Login from './Login';
    import Dashboard from './Dashboard';
    import { BrowserRouter as Router, Route} from 'react-router-dom';
    import './css/bootstrap.min.css';
    import './css/font-awesome.min.css';
    import './css/style.css';
    import { createHistory, useBasename } from 'history'
    const history = useBasename(createHistory)({
        basename: '/'
    })   
    ReactDOM.render((
      <Router history={history}>
        <div>
           <Route   path="/" component={Login} />
           <Route path="dashboard" component={Dashboard} store={Dashboard} />
           <Route exact path="login" component={Login} store={Login} />
        </div>
      </Router>
    ),
      document.getElementById('root')
    );
    

    This is my login page. But clicking on the button doesn't redirect to the corresponding component.

    import React, { Component } from 'react';
    export default class Login extends Component {
    constructor (props){
            super(props);
            this.state = {
                email : '',
                password : '',
                userId : ''
            };
        }
        login(){
          //this.props.router.push('/dashboard'); // Its was not working
          this.props.history.push('dashboard'); //Its working for me
        }
     render() {
        return (
        <div className="container-fluid">
        <div className="row">
            <div className="col-xl-12">    
                <div className="login-page-block-inner">
                    <div className="login-page-block-form">
                            <div className="form-actions">
                                <button type="button"  className="btn btn-primary width-150" onClick={(e) => { this.login()} }>Sign In</button>
                            </div>                       
                    </div>
                </div>
            </div>
        </div>
    </div>
        );
      }
    }
    
  • Eswaran Arumugam almost 5 years
    Thanks for your valuable time @Shubham. It's throws error like "Uncaught TypeError: Cannot read property 'push' of undefined"
  • Shubham Khatri
    Shubham Khatri almost 5 years
    Did you import withRouter and use it also remove export default before creating Login component
  • Eswaran Arumugam almost 5 years
    I have copied your answers and pasted it. But its not working.
  • Shubham Khatri
    Shubham Khatri almost 5 years
    I updated the code to import withRouter from 'react-router' instead of 'react-router-dom'
  • Shubham Khatri
    Shubham Khatri almost 5 years
    can you console.log(this.props) and see what you get
  • Shubham Khatri
    Shubham Khatri almost 5 years
    Yeah because it's custom history that you are using , history is the right prop

Related