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();
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
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
};
Summary
useNavigate → Get the function
navigate("/path") → Navigate to the page
navigate(/cards/${data.userId}) → Dynamically navigate using the input value
Top comments (0)