DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

How to use useNavigate to transition from a button in React

Introduction

react-router-dom's useNavigate is a useful tool for implementing page transitions in React.

It's often used in cases like "navigating to another page when a button is pressed" or "dynamically switching pages using an input ID."

This article clearly explains the basic usage of navigate and how to combine it with forms and input values.

Preparation

1.First, obtain the function with useNavigate.

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

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

2.Navigate to a fixed page

To navigate to a specific route, simply pass a string.

navigate("/cards/register"); // Navigate to the new registration page
Enter fullscreen mode Exit fullscreen mode

3.Passing values ​​dynamically

Using template literals, you can embed input values ​​in the URL.

const onSubmit = (data: any) => {
navigate(`/cards/${data.userId}`);
// Example: If userId is "hello", navigate to /cards/hello
};
Enter fullscreen mode Exit fullscreen mode

Summary

  • useNavigate → Get the function

  • navigate("/path") → Navigate to the page

  • navigate(/cards/${data.userId}) → Dynamically navigate using the input value

Top comments (0)