React Router Navigation: useNavigate Hook and Navigate Component
useNavigate Hook
The useNavigate
hook allows programmatic navigation in React Router. It is useful when you need to navigate dynamically based on user interactions, such as clicking a button.
-
Setting Dynamic Params
import { useNavigate } from "react-router-dom";
function Home() {
const navigate = useNavigate();
return <button onClick={() => navigate("/post/123")}>Go to Post 123</button>;
} -
Setting Search Params
function SearchButton() {
const navigate = useNavigate();
return <button onClick={() => navigate("/search?query=react")}>Search React</button>;
} -
Setting Fragments
function NavigateToContact() {
const navigate = useNavigate();
return <button onClick={() => navigate("#contact")}>Go to Contact</button>;
}
Navigate Component
The Navigate
component is used to perform navigation declaratively. It can be useful for redirects, such as redirecting users to a login page when they are not authenticated.
import { Navigate } from "react-router-dom";
function ProtectedRoute({ user, children }) {
if (!user) {
return <Navigate to="/login" replace />;
}
return children;
}
In this example, if the user
is not authenticated, they will be redirected to the login page.