score:0

you can't use hooks in a class component, it can only be used in just functional components. that's why you are getting this error.

you can redirect in class components by using

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

<redirect to="/dashboard" />

score:0

you cannot use hooks like 'usehistory' in class based component, so change your handlesubmit function to something like this:

handlesubmit(e) {
        e.preventdefault();

        //const history = usehistory();
        this.setstate({ submitted: true });
        const { username, password } = this.state;
        const { dispatch } = this.props;
        let errors = {};

        if (username == "admin" && password == "admin") {

            props.history.push('/dashboard');
            console.log("logged-in");

        } else {

            errors["credentials"] = "you have entered the wrong username or password.";

        }

        this.setstate({
            errors: errors
        });

    }

you can use props.history.push

score:0

when you have used a class component you cant use hook in react so you need to used another thing like if the component that is used inside the route is in the browser route you can this.props.history.push('your location')if not found like that

<route to="login" component={login}/>

else you can use this shape <redirect to="/dashboard" />

score:1

react hooks aren't compatible with class-components, they can only be used by function components and custom react hooks, so you will need to access the history object another way.

  1. if login component is directly rendered by a route component, i.e. <route path="......" component={login} /> then route props are already injected as props. you can safely access this.props.history and issue the imperative navigation.

    handlesubmit(e) {
      e.preventdefault();
    
      this.setstate({ submitted: true });
      const { username, password } = this.state;
      const { dispatch, history } = this.props; // <-- destructure
      const errors = {};
    
      if (username == "admin" && password == "admin") {
        history.push('/dashboard'); // <-- navigate
      } else {
        errors["credentials"] = "you have entered the wrong username or password.";
        this.setstate({ errors }); // <-- move error state update here
      }
    }
    
  2. use the withrouter higher order component to inject the route props, then access the history object as above.

    import { withrouter } from 'react-router-dom';
    
    ...
    
    export default withrouter(login);
    

    don't forget to update and default import login here it's rendered.


Related Query

More Query from same tag