Programmatic Navigation and Redirects
×


Programmatic Navigation and Redirects

659

🚀 What Is Programmatic Navigation?

In React applications, programmatic navigation lets you navigate between pages using logic in your code — rather than just clicking links. This is useful for use cases like form submissions, login redirects, conditional routing, or logout flows. 🧠

📦 React Router’s useNavigate Hook

React Router v6+ introduces the useNavigate hook, replacing the older useHistory from v5. It gives you full control over routing in JavaScript.


import { useNavigate } from 'react-router-dom';

function MyComponent() {
  const navigate = useNavigate();

  const goToDashboard = () => {
    navigate('/dashboard');
  };

  return <button onClick={goToDashboard}>Go to Dashboard</button>;
}

🔁 Navigating After Events

Programmatic navigation is commonly used after:

  • ✅ Form submissions
  • ✅ Successful login/signup
  • ✅ Completing a checkout


function handleSubmit(e) {
  e.preventDefault();
  // validate or send data
  navigate('/success');
}

📥 Passing Data While Navigating

You can pass data using state:


navigate('/thank-you', { state: { userName: 'Aditya' } });
And retrieve it using the useLocation hook:

import { useLocation } from 'react-router-dom';

function ThankYouPage() {
  const location = useLocation();
  const { userName } = location.state || {};

  return <h2>Thanks, {userName}!</h2>;
}

🔙 Navigating Backward or Forward

You can simulate browser history actions:


navigate(-1); // Go back
navigate(1);  // Go forward

â›” Redirecting Unauthorized Users

To redirect users conditionally (e.g., if not logged in), just use:


if (!isLoggedIn) {
  navigate('/login');
}
You can also use the <Navigate /> component for static redirects:

import { Navigate } from 'react-router-dom';

function PrivateRoute({ isAuth, children }) {
  return isAuth ? children : <Navigate to="/login" replace />;
}

🧠 Redirect on Mount

Use a useEffect for automatic redirection when a component mounts:


import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

function RedirectPage() {
  const navigate = useNavigate();

  useEffect(() => {
    navigate('/home');
  }, []);

  return null;
}

🧭 Replace vs Push Navigation

By default, navigate() pushes to browser history. You can also replace the current entry:


navigate('/login', { replace: true }); // Won't keep previous page in history
This is useful for login redirects, so users can't press "Back" and go to the protected page again. 🔐

📋 Summary

  • ✅ Use useNavigate() for full control over navigation
  • ✅ Trigger redirects after events like login or submission
  • ✅ Pass and receive data via state
  • ✅ Replace history for secure redirects
  • ✅ Use <Navigate /> for static route guarding

🚀 Final Thoughts

Programmatic navigation is a core part of building dynamic React applications. With useNavigate and <Navigate />, you can control user flow, enforce security, and build seamless UX transitions — all in just a few lines of code. 🔄⚛️



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat