Links allow users to navigate through different parts of your site, but what if the application itself needs to navigate dynamically? React Router provides the Navigate component and the useNavigate hook to enable programmatic navigation.
By the end of this reading, you should be able to:
Navigate component to redirect usersuseNavigate hook for programmatic navigationThe Navigate component allows you to redirect users to a specific route.
import { createBrowserRouter, RouterProvider, Navigate } from 'react-router-dom';
const router = createBrowserRouter([
{ path: 'home', element: },
{ path: 'teams', element: },
{ path: '*', element: }
]);
function App() {
return
}
export default App;
In this example:
/home or /teams will redirect to /home.replace prop ensures that the browser's back button does not navigate back to an invalid route.The useNavigate hook provides navigation functionality without needing to render a component.
import { useNavigate } from 'react-router-dom';
function MyForm() {
const navigate = useNavigate();
const handleSubmit = () => {
// Process form submission...
navigate('/home');
}
return (
);
}
In this example:
navigate('/home') redirects the user to the home page.The navigate function supports an options object:
navigate('/home', { replace: true });
This replaces the current entry in the browser’s history, preventing users from navigating back to the previous page.
The navigate function can take a numerical argument to move back or forward in history:
navigate(-1); // Goes back one page
navigate(1); // Goes forward one page
In this reading, you learned how to:
Navigate component for redirectionsuseNavigate hook for programmatic navigationreplace and numerical argumentsTo deepen your understanding, explore these topics:
React Router’s navigation features allow for seamless and dynamic user experiences. By leveraging Navigate and useNavigate, developers can control page transitions and enhance application flow.