React Router Navigation and Redirects

Building dynamic React applications often necessitates controlling how users move between different sections of your website. React Router is a powerful library that simplifies routing, but it also provides tools for programmatic navigation (using the navigate function) and automatic redirects (using <Navigate> and related techniques). In this post, we’ll explore both concepts and see how they work in practice, especially with the latest version of React Router (v6).

“react router navigate”

The navigate function in React Router lets you change the current URL and trigger a navigation within your React app, even from outside of your React components.

Core Usage:

JavaScript

import { useNavigate } from ‘react-router-dom’;

function MyComponent() {

  const navigate = useNavigate();

  const handleButtonClick = () => {

    navigate(‘/profile’); // Navigates to the ‘/profile’ route

  };

  return (

    <button onClick={handleButtonClick}>Go to Profile</button>

  );

}

Common Use Cases:

  • Form Submissions: Redirect to a success page after form submission.
  • Data Fetching: Navigate to a content page after data is loaded.
  • Event Handling: Navigate in response to any button clicks or user interactions.

Options

  • replace: true: Replace the current history entry instead of pushing a new one (useful to prevent the back button from returning to the previous form page).

“react router redirect”

Redirects automatically send users to a different route based on conditions you define.

React Router v5 (Older)

Prior to v6, the <Redirect> component was the standard:

JavaScript

import { Redirect } from ‘react-router-dom’; 

<Route path=”/old-page”>

  <Redirect to=”/new-page” />

</Route>

React Router v6 (Current)

  • <Navigate> Component: Used within JSX for in-component redirects.
  • JavaScript
  • import { Navigate } from ‘react-router-dom’;
  • function HomePage() {
  •   const isLoggedIn = false; 
  •   if (!isLoggedIn) {
  •     return <Navigate to=”/login” replace />; 
  •   }
  •   // … Rest of home page content
  • }
  • useNavigate Hook: For redirects outside of components or more complex logic handling

Conditional Redirects

Route protection based on authentication is a common redirect use case. See the HomePage example above for a basic structure.