Home > Blockchain >  How to redirect user to another page in react on handleSubmit if I use class component?
How to redirect user to another page in react on handleSubmit if I use class component?

Time:12-26

I want to redirect the user at the end of the handleSubmit function

class Singup extends Component {

  ...

  handleSubmit = async (e) => {

    ...

    useNavigate(("/"));

    **// I want to redirect user here**

};
  render() {

  ...

  }
}

ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

CodePudding user response:

Hooks need to declare in the component level

class Singup extends Component {

  const navigate = useNavigate();

  ...

  handleSubmit = async (e) => {

    ...

    navigate("/");

    **// I want to redirect user here**

};

CodePudding user response:

Try like this (Also corrected class name spelling):

You have to use Navigate component with state for class component and react-router-dom (version 6).

import { Navigate } from "react-router-dom";

class Signup extends Component {

 state = { user: false };

 handleSubmit = async (e) => {

  // Your code

  this.setState({ user: true });
  **// I want to redirect user here**

};

In Render part use Navigate component like this:

{this.state.user && (
      <Navigate to="/" replace={true} />
    )}
  • Related