React Router - Navigation

Understanding Navigation in React Router

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.

Learning Goals

By the end of this reading, you should be able to:

Using the Navigate Component

The 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:

Using useNavigate for Programmatic Navigation

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 (
    
{/* Form fields here */}
); }

In this example:

Using Navigation Options

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.

Navigating Through Browser History

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
    

What You Have Learned

In this reading, you learned how to:

Further Exploration

To deepen your understanding, explore these topics:

Conclusion

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.