React Router navigation using history push

Viewed 11007

I am new to ReactJS. I stuck with React routing when i tried to navigate from one page to another page history.push('/newpage') is not working for me. Login service call success i want navigate to another page.

I am using below version

"react": "^16.13.1", "react-dom": "^16.13.1", "react-router-dom": "^5.2.0",

import React, { Component } from 'react';
import { useHistory } from 'react-router-dom';
import '../Login/Login.css';
import {Auth} from '../../services/Api';
// import { Redirect } from 'react-router-dom'
class Login extends Component {

    constructor(props) {
        super(props)
        this.state = {
            userName: '',
            password: ''
        }
        this.changeEventReact = this.changeEventReact.bind(this);
        this.login = this.login.bind(this);
    }
    changeEventReact = (e) =>{
        this.setState({[e.target.name]: e.target.value});
        // console.log(this.state);
    }
    login = e=>{
        // console.log(this.state);
        Auth('login', this.state)
        .then((result)=>{
            let responseJSON = result;
            if(responseJSON.data.id != ''){
                console.log("Login success");
                const history = useHistory();
                let path = `/facilityRegister`; 
                history.push(path);
            }else{
                console.log('Login failed');
            }
        });
    }

We can use below three methods to do this

1. history.push('/facilityRegister')
2. <Redirect to='/facilityRegister'/>
3. window.location.href("/facilityRegister')

window.location.href is working as expected. But history.push and is not working.

Let me know what I missed.

2 Answers

According to react faq:

You can’t use Hooks inside a class component

That's why const history = useHistory(); is not working here. But anyway you can't use hooks inside async functions. Use withRouter HOC instead or try to rewrite your component to functional.

well as say before hooks can not be use in class components and can only be use in function components like this

const app = (props) => {
     const history = useHistory();
     history.push("/path");
}

you can try this props.history.push("/path")

hope it's help :)

Related