JavaScript and React course ยท Module 6: React Router

Programmatic Navigation in Cosmic Travels

11 min read ยท
In this lesson9

In the spaceship command center, we sometimes need to navigate between different locations not only using buttons and links, but also programmatically - based on specific conditions, events, or application logic. React Router provides advanced tools for such programmatic navigation, allowing you to control the user's route from the code level.

Introduction to Programmatic Navigation

Programmatic navigation is a technique for changing the URL address and rendered view using JavaScript code, without direct user interaction with links or buttons. It is an essential element of many application scenarios:

  • Redirecting after successful login
  • Navigation after completing a multi-step form
  • Returning after saving data
  • Redirecting after session timeout
  • Navigation based on API responses

In React Router, the main tool for programmatic navigation is the useNavigate hook.

The useNavigate Hook

The useNavigate hook introduced in React Router v6 provides a function that allows programmatically navigating to other paths in the application:

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

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

  const handleMissionStart = () => {
    // Mission start logic...
    console.log('Mission started!');

    // After starting the mission, redirect to the monitoring panel
    navigate('/mission/monitoring');
  };

  return (
    <div className="launch-control">
      <h2>Launch Control Panel</h2>
      <button
        className="launch-button"
        onClick={handleMissionStart}
      >
        Start Mission
      </button>
    </div>
  );
}

Basic Usage of navigate

The navigate function can accept different arguments:

  1. Target path as a string:
// Navigate to a specific path
navigate('/planets/mars');

// Relative navigation (one level up)
navigate('..');

// Relative navigation (to a sub-path)
navigate('systems');
  1. A number (delta) for history navigation:
// Go back one page (like the browser's "back" button)
navigate(-1);

// Go forward one page (like the browser's "forward" button)
navigate(1);

// Go back two pages
navigate(-2);
  1. An object with options:
// Navigation with options
navigate('/planets/mars', {
  replace: true,  // Replaces the current history entry instead of adding a new one
  state: { prevLocation: '/dashboard' }  // State data to pass
});

// Navigation with search parameters
navigate({
  pathname: '/planets',
  search: '?type=rocky&habitable=true'
});

The replace Option

By default, navigate adds a new entry to the browser history. This means the user can return to the previous page using the "back" button. Sometimes, however, we want to replace the current entry so the user can't go back (e.g., after logging out):

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

  const handleLogout = () => {
    // Log out the user
    logout();

    // Redirect to the login page, replacing the current entry in history
    navigate('/login', { replace: true });
  };

  return <button onClick={handleLogout}>Logout</button>;
}

Passing State Through Navigation

We can pass state data to a new location using the state option. This data is not visible in the URL, but is available in the target component:

// Source component
function PlanetsList() {
  const navigate = useNavigate();

  const viewPlanetDetails = (planet) => {
    navigate(`/planets/${planet.id}`, {
      state: {
        planetData: planet,
        viewedFrom: 'planetsList',
        timestamp: Date.now()
      }
    });
  };

  return (
    <div>
      {planets.map(planet => (
        <div key={planet.id} onClick={() => viewPlanetDetails(planet)}>
          {planet.name}
        </div>
      ))}
    </div>
  );
}

// Target component
function PlanetDetails() {
  const { state } = useLocation();
  const { planetId } = useParams();

  useEffect(() => {
    if (state?.viewedFrom) {
      console.log(`Redirected from: ${state.viewedFrom}`);
      console.log(`Planet data from navigation: ${state.planetData}`);
    }
  }, [state]);

  return (
    <div>
      <h1>Planet details: {planetId}</h1>
      {/* Rest of the component */}
    </div>
  );
}

Building Advanced Navigation Mechanisms

Using the useNavigate hook, we can build advanced navigation mechanisms that handle complex user flows:

1. Conditional Redirects

function ResourceLoader({ resourceId, resourceType }) {
  const navigate = useNavigate();
  const [resource, setResource] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchResource(resourceId, resourceType)
      .then(data => {
        setResource(data);

        // Conditionally redirect based on resource type
        if (resourceType === 'mission' && data.status === 'in-progress') {
          navigate(`/mission-control/${resourceId}`);
        } else if (resourceType === 'planet' && data.isRestricted) {
          navigate('/access-denied', {
            replace: true,
            state: { reason: 'restricted-planet' }
          });
        }
      })
      .catch(err => {
        setError(err);

        // Redirect to error page in case of a problem
        navigate('/error', {
          state: {
            error: err.message,
            resourceId,
            resourceType
          }
        });
      });
  }, [resourceId, resourceType, navigate]);

  if (error) return <p>Loading...</p>;
  if (!resource) return <p>Loading...</p>;

  return <ResourceViewer resource={resource} />;
}

2. Controlled Multi-step Flow

function MissionPlanner() {
  const navigate = useNavigate();
  const [currentStep, setCurrentStep] = useState(1);
  const [missionData, setMissionData] = useState({});

  const handleStepComplete = (stepData) => {
    // Update mission data with data from the current step
    const updatedData = { ...missionData, ...stepData };
    setMissionData(updatedData);

    if (currentStep < 3) {
      // Move to the next step
      setCurrentStep(currentStep + 1);
    } else {
      // All steps completed, save mission and redirect
      saveMission(updatedData)
        .then(mission => {
          navigate(`/missions/${mission.id}/overview`, {
            state: { missionData: mission, isNewMission: true }
          });
        })
        .catch(error => {
          navigate('/error', { state: { error } });
        });
    }
  };

  const handleCancel = () => {
    // Ask the user if they really want to cancel
    if (window.confirm('Are you sure you want to cancel mission planning?')) {
      navigate('/missions');
    }
  };

  return (
    <div className="mission-planner">
      <h1>Planning a New Mission</h1>
      <ProgressBar currentStep={currentStep} totalSteps={3} />

      {currentStep === 1 && (
        <MissionBasicInfoStep
          onComplete={handleStepComplete}
          initialData={missionData}
        />
      )}

      {currentStep === 2 && (
        <MissionCrewSelectionStep
          onComplete={handleStepComplete}
          initialData={missionData}
        />
      )}

      {currentStep === 3 && (
        <MissionConfirmationStep
          onComplete={handleStepComplete}
          initialData={missionData}
        />
      )}

      <div className="actions">
        {currentStep > 1 && (
          <button onClick={() => setCurrentStep(currentStep - 1)}>
            Back
          </button>
        )}

        <button onClick={handleCancel}>Cancel</button>
      </div>
    </div>
  );
}

3. Time-based Redirects

function SessionTimer() {
  const navigate = useNavigate();
  const [timeLeft, setTimeLeft] = useState(300); // 5 minutes

  useEffect(() => {
    if (timeLeft <= 0) {
      // Session expired, redirect to login page
      alert('Your session has expired. Please log in again.');
      navigate('/login', {
        replace: true,
        state: { sessionExpired: true }
      });
      return;
    }

    // Update timer every second
    const timer = setTimeout(() => {
      setTimeLeft(timeLeft - 1);
    }, 1000);

    return () => clearTimeout(timer);
  }, [timeLeft, navigate]);

  const formatTime = () => {
    const minutes = Math.floor(timeLeft / 60);
    const seconds = timeLeft % 60;
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  };

  return (
    <div className="session-timer">
      <span>Remaining session time: {formatTime()}</span>
    </div>
  );
}

A very common use case for programmatic navigation is redirecting based on API responses. Here are a few typical scenarios:

1. Redirect After Successful Form Submission

function NewPlanetForm() {
  const navigate = useNavigate();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState(null);

  const handleSubmit = async (event) => {
    event.preventDefault();
    setIsSubmitting(true);
    setError(null);

    try {
      const formData = new FormData(event.target);
      const planetData = {
        name: formData.get('name'),
        type: formData.get('type'),
        diameter: Number(formData.get('diameter')),
        hasWater: formData.get('hasWater') === 'on'
      };

      // Send data to API
      const response = await fetch('/api/planets', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(planetData)
      });

      if (!response.ok) {
        throw new Error('Error adding planet');
      }

      const newPlanet = await response.json();

      // Redirect to the new planet's details page
      navigate(`/planets/${newPlanet.id}`, {
        state: {
          message: 'Planet has been successfully added!',
          planetData: newPlanet
        }
      });
    } catch (err) {
      setError(err.message);
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields */}
      {error && <div className="error">{error}</div>}
      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? 'Adding...' : 'Add planet'}
      </button>
    </form>
  );
}

2. Redirect After Successful Login

function LoginForm() {
  const navigate = useNavigate();
  const location = useLocation();

  // Check if the user was redirected from another page
  const from = location.state?.from?.pathname || '/dashboard';

  const handleSubmit = async (event) => {
    event.preventDefault();
    const formData = new FormData(event.target);

    try {
      // Call login API
      const user = await loginUser(
        formData.get('username'),
        formData.get('password')
      );

      // Save user data in application state
      setUserInContext(user);

      // Redirect to original location or dashboard
      navigate(from, { replace: true });
    } catch (error) {
      // Handle login error
      //
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Login form fields */}
    </form>
  );
}

Route Guards

Using useNavigate, we can create route guards that automatically redirect the user if they don't meet certain conditions. This technique is often used to protect routes that require authentication:

function RequireAuth({ children }) {
  const navigate = useNavigate();
  const location = useLocation();
  const { user } = useAuth();

  useEffect(() => {
    if (!user) {
      // Redirect to login page, preserving information
      // about where the user came from so we can return them after login
      navigate('/login', {
        replace: true,
        state: { from: location }
      });
    }
  }, [user, navigate, location]);

  // If the user is logged in, render children (the protected route)
  return user ? children : null;
}

// Usage in route definition
<Route
  path="/mission-control"
  element={
    <RequireAuth>
      <MissionControlPanel />
    </RequireAuth>
  }
/>

We can use navigate to navigate with search parameters, which is useful for filtering, sorting, and pagination:

function GalaxiesExplorer() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  // Read current filters from URL
  const currentType = searchParams.get('type') || 'all';
  const currentSort = searchParams.get('sort') || 'name';

  const applyFilters = (filters) => {
    // Create a new URLSearchParams object
    const params = new URLSearchParams();

    // Add filters to parameters
    if (filters.type && filters.type !== 'all') {
      params.set('type', filters.type);
    }

    if (filters.sort) {
      params.set('sort', filters.sort);
    }

    // Navigate to the same path but with new parameters
    navigate({
      pathname: '/galaxies',
      search: params.toString() ? `?${params.toString()}` : ''
    });
  };

  return (
    <div className="galaxies-explorer">
      <div className="filters">
        <label>
          Galaxy type:
          <select
            value={currentType}
            onChange={(e) => applyFilters({
              type: e.target.value,
              sort: currentSort
            })}
          >
            <option value="all">All</option>
            <option value="spiral">Spiral</option>
            <option value="elliptical">Elliptical</option>
            <option value="irregular">Irregular</option>
          </select>
        </label>

        <label>
          Sort by:
          <select
            value={currentSort}
            onChange={(e) => applyFilters({
              type: currentType,
              sort: e.target.value
            })}
          >
            <option value="name">Name</option>
            <option value="size">Size</option>
            <option value="distance">Distance</option>
          </select>
        </label>
      </div>

      {/* Galaxy list */}
    </div>
  );
}

Using navigate with URL Generator

We can combine navigate with the createSearchParams function for easier creation of search parameters:

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

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

  const applyFilters = (filters) => {
    // Use createSearchParams to generate a parameters string
    const params = createSearchParams({
      type: filters.type,
      hasWater: filters.hasWater ? 'true' : undefined,
      minDiameter: filters.minDiameter,
      sortBy: filters.sortBy
    });

    navigate({
      pathname: '/planets',
      search: `?${params}`
    });
  };

  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      applyFilters({
        type: e.target.type.value,
        hasWater: e.target.hasWater.checked,
        minDiameter: e.target.minDiameter.value,
        sortBy: e.target.sortBy.value
      });
    }}>
      {/* Filter form fields */}
      <button type="submit">Apply filters</button>
    </form>
  );
}

Problems and Pitfalls of Programmatic Navigation

1. Redirects During Rendering

Avoid using navigate directly during component rendering - it causes problems with multiple re-renders. Instead, use navigate in effects, event handlers, or callbacks:

// BAD - causes infinite render loop
function BadComponent() {
  const navigate = useNavigate();

  if (!userIsAuthenticated) {
    navigate('/login'); // This will be called during every render!
  }

  return <div>Protected content</div>;
}

// GOOD - uses useEffect
function GoodComponent() {
  const navigate = useNavigate();

  useEffect(() => {
    if (!userIsAuthenticated) {
      navigate('/login');
    }
  }, [navigate, userIsAuthenticated]);

  return <div>Protected content</div>;
}

2. Lost State Data

Remember that data passed through navigate in state is lost on page refresh. For data that must survive a refresh, use URL parameters or store them in local storage:

// Data will be lost on refresh
navigate('/dashboard', { state: { importantData: data } });

// Better for important data
// 1. Use URL parameters
navigate(`/dashboard?dataId=${dataId}`);

// 2. Or save in localStorage
localStorage.setItem('importantData', JSON.stringify(data));
navigate('/dashboard');

3. Problems with Asynchronous Redirects

Sometimes we want to redirect the user after an asynchronous operation completes. Be careful about potential issues when the component unmounts before the operation completes:

function AsyncNavigation() {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);

  const handleClick = async () => {
    setIsLoading(true);

    try {
      // Asynchronous operation
      await someAsyncOperation();

      // The component may already be unmounted at this point!
      // If using React 18 with Strict Mode, this may cause issues
      navigate('/success');
    } catch (error) {
      setIsLoading(false);
      // Handle error
    }
  };

  return (
    <button onClick={handleClick} disabled={isLoading}>
      {isLoading ? 'Loading...' : 'Execute operation'}
    </button>
  );
}

The solution is to use flags to track whether the component is still mounted:

function SafeAsyncNavigation() {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  const isMounted = useRef(true);

  useEffect(() => {
    return () => {
      // Mark component as unmounted during cleanup
      isMounted.current = false;
    };
  }, []);

  const handleClick = async () => {
    setIsLoading(true);

    try {
      await someAsyncOperation();

      // Check if the component is still mounted
      if (isMounted.current) {
        navigate('/success');
      }
    } catch (error) {
      if (isMounted.current) {
        setIsLoading(false);
      }
    }
  };

  return (
    <button onClick={handleClick} disabled={isLoading}>
      {isLoading ? 'Loading...' : 'Execute operation'}
    </button>
  );
}

Summary

Programmatic navigation is a powerful tool in the React developer's arsenal, allowing for the creation of advanced user flows and responding to various events in the application. The useNavigate hook offers a flexible and intuitive API for controlling navigation:

  1. Basic redirects - simple transitions between paths
  2. Navigation with parameters - passing data through the URL
  3. State passing - invisible data available on the target page
  4. History replacement - control over the browser's history stack
  5. Conditional redirects - navigation based on business logic and API responses

Using programmatic navigation, you can build more dynamic and responsive applications that smoothly guide the user through different cosmic spaces of your application.

Code for this lesson: App.jsx
import React from 'react';
import { BrowserRouter, Routes, Route, NavLink } from 'react-router-dom';

// Navigation with NavLink
function Navigation() {
  return (
    <nav className="sidebar">
      <h2>Space Station</h2>

      <NavLink
        to="/"
        className={({ isActive }) => isActive ? 'nav-item active' : 'nav-item'}
      >
        Dashboard
      </NavLink>

      <NavLink
        to="/crew"
        className={({ isActive }) => isActive ? 'nav-item active' : 'nav-item'}
      >
        Crew
      </NavLink>

      <NavLink
        to="/missions"
        className={({ isActive }) => isActive ? 'nav-item active' : 'nav-item'}
      >
        Missions
      </NavLink>

      <NavLink
        to="/systems"
        className={({ isActive }) => isActive ? 'nav-item active' : 'nav-item'}
      >
        Systems
      </NavLink>

      <NavLink
        to="/comms"
        style={({ isActive }) => ({
          color: isActive ? '#ffd700' : '#ffa500',
          fontWeight: isActive ? 'bold' : 'normal',
          background: isActive ? 'rgba(255, 215, 0, 0.2)' : 'transparent',
        })}
        className="nav-item"
      >
        Communications
      </NavLink>
    </nav>
  );
}

// Page components
function Dashboard() {
  return (
    <div className="page">
      <h1>Dashboard</h1>
      <p>Welcome to the space station control center!</p>
      <div className="stats">
        <div className="stat"><span>Crew:</span> 6 members</div>
        <div className="stat"><span>Missions:</span> 3 active</div>
        <div className="stat"><span>Status:</span> Everything OK</div>
      </div>
    </div>
  );
}

function Crew() {
  return (
    <div className="page">
      <h1>Crew</h1>
      <ul className="crew-list">
        <li>Anna Kowalska - Commander</li>
        <li>Jan Nowak - Pilot</li>
        <li>Maria Wisniewska - Engineer</li>
        <li>Piotr Kowalczyk - Scientist</li>
      </ul>
    </div>
  );
}

function Missions() {
  return (
    <div className="page">
      <h1>Missions</h1>
      <div className="mission-list">
        <div className="mission">Apollo 25 - In progress</div>
        <div className="mission">Artemis 12 - Planning</div>
        <div className="mission">Europa Probe - Testing</div>
      </div>
    </div>
  );
}

function Systems() {
  return (
    <div className="page">
      <h1>Systems</h1>
      <div className="systems-grid">
        <div className="system ok">Power:</div>
        <div className="system ok">Life:</div>
        <div className="system ok">Navigation:</div>
        <div className="system warn">Communications:</div>
      </div>
    </div>
  );
}

function Comms() {
  return (
    <div className="page">
      <h1>Communications</h1>
      <p>Last contact with Earth: 2 minutes ago</p>
      <p>Signal strength: 87%</p>
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      <div className="app">
        <Navigation />
        <main>
          <Routes>
            <Route path="/" element={<Dashboard />} />
            <Route path="/crew" element={<Crew />} />
            <Route path="/missions" element={<Missions />} />
            <Route path="/systems" element={<Systems />} />
            <Route path="/comms" element={<Comms />} />
          </Routes>
        </main>
      </div>
    </BrowserRouter>
  );
}

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the purpose of the useNavigate hook in React Router v6?

  2. 2. The Outlet component in React Router is used for:

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Programmatic navigation

  1. QuestionHook useNavigate
  2. Coding taskPractice: Programmatic Navigation
  3. QuestionOutlet component in React Router
  4. QuestionIndex Routes

Useful articles