React Router Redirect Component

As a React developer with over a decade of experience, I’ve seen how routing and navigation have evolved in React applications. One of the common tasks when building single-page applications (SPAs) is redirecting users from one route to another. Whether it’s after a successful login, when accessing protected routes, or handling 404 pages, redirects are essential for a smooth user experience.

In this article, I’ll share practical ways to implement redirection in React using React Router. I’ll cover different methods, including the classic <Redirect> component (React Router v5) and the newer useNavigate hook (React Router v6). By the end, you’ll have a solid understanding of how to handle redirects effectively in your React projects.

What Is React Router Redirect?

React Router is the de facto standard for routing in React applications. It lets you declare routes and handle navigation without full page reloads. Redirecting means programmatically sending users from one URL to another.

In React Router v5, the <Redirect> component was the primary way to perform redirects declaratively inside your JSX. With React Router v6, the API changed, and the <Navigate> component or the useNavigate hook is now used.

Redirect in React Router v5 Using <Redirect>

If you’re maintaining a project using React Router v5, you’ll likely use the <Redirect> component. It’s straightforward and declarative.

Here’s a simple example:

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';

function Home() {
  return <h2>Welcome to the Home Page</h2>;
}

function Login() {
  const isAuthenticated = false; // Assume user is not logged in

  if (isAuthenticated) {
    return <Redirect to="/dashboard" />;
  }

  return <h2>Please log in</h2>;
}

function Dashboard() {
  return <h2>Dashboard - Protected Content</h2>;
}

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/login" component={Login} />
        <Route path="/dashboard" component={Dashboard} />
        {/* Redirect unknown routes to home */}
        <Redirect to="/" />
      </Switch>
    </Router>
  );
}

export default App;

You can see the output in the screenshot below.

React Router Redirect Component
  • In the Login component, if the user is authenticated, we redirect them to the dashboard.
  • The <Redirect to=”/” /> at the bottom handles any unmatched routes by sending users back to the home page.
  • This method is great for simple redirect needs in v5.

Redirect in React Router v6 Using <Navigate>

React Router v6 introduced breaking changes, including replacing <Redirect> with <Navigate>. It’s similar but requires some syntax updates.

Here’s how you can do the same example with React Router v6:

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';

function Home() {
  return <h2>Welcome to the Home Page</h2>;
}

function Login() {
  const isAuthenticated = false; // Assume user is not logged in

  if (isAuthenticated) {
    return <Navigate to="/dashboard" replace />;
  }

  return <h2>Please log in</h2>;
}

function Dashboard() {
  return <h2>Dashboard - Protected Content</h2>;
}

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route path="/dashboard" element={<Dashboard />} />
        {/* Redirect unknown routes to home */}
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </Router>
  );
}

export default App;

You can see the output in the screenshot below.

Router Redirect Component in React
  • The <Navigate> component replaces <Redirect>.
  • The replace prop prevents adding a new entry in the history stack, which is often desirable for redirects.
  • The wildcard route path=”*” catches all unmatched routes and redirects to the home.

Programmatic Redirects Using useNavigate Hook (React Router v6)

Sometimes, you want to redirect users in response to an event, like a button click or after a form submission. React Router v6 provides the useNavigate hook for this purpose.

Here’s an example simulating a login flow:

import React, { useState } from 'react';
import { BrowserRouter as Router, Routes, Route, useNavigate } from 'react-router-dom';

function Login() {
  const [username, setUsername] = useState('');
  const navigate = useNavigate();

  const handleLogin = () => {
    // Mock authentication logic
    if (username === 'admin') {
      // Redirect to dashboard after login
      navigate('/dashboard', { replace: true });
    } else {
      alert('Invalid username');
    }
  };

  return (
    <div>
      <h2>Login</h2>
      <input 
        type="text" 
        placeholder="Enter username" 
        value={username} 
        onChange={(e) => setUsername(e.target.value)} 
      />
      <button onClick={handleLogin}>Log In</button>
    </div>
  );
}

function Dashboard() {
  return <h2>Dashboard - Welcome Admin!</h2>;
}

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="*" element={<Login />} />
      </Routes>
    </Router>
  );
}

export default App;

You can see the output in the screenshot below.

Router Redirect Component React
  • The useNavigate hook returns a navigate function.
  • Calling navigate(‘/dashboard’) changes the route programmatically.
  • The replace: true option ensures the redirect doesn’t add a new history entry.

Redirect After Form Submission: A Real-World Scenario

Imagine you’re building a job application portal for a US-based company. After submitting an application form, you want to redirect the user to a confirmation page.

Here’s how you can do it:

import React, { useState } from 'react';
import { BrowserRouter as Router, Routes, Route, useNavigate } from 'react-router-dom';

function JobApplication() {
  const [name, setName] = useState('');
  const navigate = useNavigate();

  const handleSubmit = (e) => {
    e.preventDefault();
    // Mock submitting data to server
    console.log(`Application submitted by ${name}`);
    // Redirect to confirmation page
    navigate('/confirmation');
  };

  return (
    <form onSubmit={handleSubmit}>
      <h2>Job Application</h2>
      <input 
        type="text" 
        placeholder="Full Name" 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
        required 
      />
      <button type="submit">Submit Application</button>
    </form>
  );
}

function Confirmation() {
  return <h2>Thank you for your application! We will be in touch soon.</h2>;
}

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<JobApplication />} />
        <Route path="/confirmation" element={<Confirmation />} />
      </Routes>
    </Router>
  );
}

export default App;

This pattern is pervasive in real-world applications, especially in the US job market portals and e-commerce checkout flows.

Handle Protected Routes with Redirects

Redirecting unauthenticated users away from protected pages is a must-have feature. Here’s a simple way to implement it:

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';

const isAuthenticated = false; // Replace with real auth check

function ProtectedRoute({ children }) {
  return isAuthenticated ? children : <Navigate to="/login" replace />;
}

function Dashboard() {
  return <h2>Dashboard - Protected Content</h2>;
}

function Login() {
  return <h2>Please log in to access the dashboard.</h2>;
}

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route 
          path="/dashboard" 
          element={
            <ProtectedRoute>
              <Dashboard />
            </ProtectedRoute>
          } 
        />
        <Route path="*" element={<Navigate to="/login" replace />} />
      </Routes>
    </Router>
  );
}

export default App;
  • The ProtectedRoute component checks authentication.
  • If not authenticated, it redirects to the login page.
  • This pattern is essential for any secure React app.

Using React Router’s redirect capabilities correctly ensures your users have a seamless navigation experience. Whether you’re working on legacy React Router v5 projects or the latest v6 apps, these techniques will help you manage routing like a pro.

If you want to dive deeper, remember to check React Router’s official documentation and keep your dependencies up to date.

You may also like to read the other articles on React:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.