DEV Community

Joshua Campos
Joshua Campos

Posted on

How to redirect to another page when we click a button on a form with react-router-dom@v5

Lets say we create a form for a login page and when we clicked the div element to sign up, we want to redirect our page to "/createuser" page.

Image description

  • We can import the useHistory hook from react-router-dom:

Image description

  • We can declare the useHistory in a const variable:

Image description

  • We add an event listener to our div, so that it can listen for a click and then passed in a callback function and then push the url route we want our form to redirect to once we click the sign up div to the useHistory that we declared inside the navigation variable.

Image description

Note that the useHistory() is for react-router-dom@5

If you are using the newer version then instead of using the useHistory Hook you can use the useNavigate Hook.

for example:

For the V5

const navigate = usehistory();
navigate.push("/");
Enter fullscreen mode Exit fullscreen mode

For the V6

const navigate = useNavigate();
navigate("/")
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)