JavaScript and React course ยท Module 6: React Router

URL Parameters in Cosmic Navigation

12 min read ยท
In this lesson10

In interplanetary travels, coordinates and identifiers of celestial bodies are key to navigation. Similarly in React Router, URL parameters allow for precisely directing the user to specific application resources. In this module, we'll learn how to use, read, and manipulate URL parameters in our space applications.

What are URL Parameters?

URL parameters are variable parts of a URL address that can contain dynamic values. In React Router, they come in two main forms:

  1. Path parameters - embedded in the URL structure (e.g., /planets/:planetId)
  2. Query parameters - added after the question mark (e.g., /planets?type=rocky&inhabited=true)

Path Parameters

Path parameters are part of the URL structure itself and are defined by a colon (:) in the route definition.

Defining Routes with Path Parameters

import { Routes, Route } from 'react-router-dom';

function AppRoutes() {
  return (
    <Routes>
      <Route path="/" element={<Dashboard />} />
      <Route path="/planets/:planetId" element={<PlanetDetails />} />
      <Route path="/missions/:year/:missionId" element={<MissionDetails />} />
    </Routes>
  );
}

In the example above:

  • :planetId is a parameter in the path /planets/:planetId
  • :year and :missionId are parameters in the path /missions/:year/:missionId

These paths will match URLs such as:

  • /planets/mars
  • /planets/jupiter
  • /missions/2150/mars-expedition

Accessing Path Parameters with useParams

To read path parameter values in a component, we use the useParams hook:

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

function PlanetDetails() {
  const { planetId } = useParams();

  return (
    <div className="planet-details">
      <h1>Planet details: {planetId}</h1>
      {/* Rest of the component using the planetId value */}
    </div>
  );
}

In a more complex component, we can use the parameter to fetch data:

import { useParams } from 'react-router-dom';
import { useState, useEffect } from 'react';

function PlanetDetails() {
  const { planetId } = useParams();
  const [planetData, setPlanetData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Reset state when parameter changes
    setLoading(true);
    setError(null);

    // Fetch data for the specific planet
    fetch(`https://api.space-explorer.com/planets/${planetId}`)
      .then(response => {
        if (!response.ok) {
          throw new Error('Unable to fetch planet data');
        }
        return response.json();
      })
      .then(data => {
        setPlanetData(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, [planetId]); // Re-run the effect when planetId changes

  if (loading) return <div>Loading planet data...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!planetData) return <div>Planet not found</div>;

  return (
    <div className="planet-details">
      <h1>{planetData.name}</h1>
      <div className="planet-info">
        <p>Diameter: {planetData.diameter} km</p>
        <p>Distance from the Sun: {planetData.distanceFromSun} million km</p>
        <p>Surface temperature: {planetData.surfaceTemperature}ยฐC</p>
        <p>Type: {planetData.type}</p>
      </div>
      {/* More information about the planet */}
    </div>
  );
}

Optional Path Parameters

The mission log has two views: a list of all missions at /missions and the missions from a single year, e.g. /missions/2150. So the year is sometimes in the address and sometimes not. Since version 6.5 (December 2022, and the same in v7 and v8), React Router lets you mark such a segment as optional: just add a question mark at its end.

<Routes>
  <Route path="/missions/:year?" element={<MissionsList />} />
</Routes>

One route now handles both addresses: /missions and /missions/2150. The question mark applies only to the segment it is attached to, which is why /missions/2150/06 does not match this route. The /missions/:year?/:month? pattern from the routing configuration lesson works the same way: each of the two segments is optional on its own.

You read the parameter as before, with the useParams hook. The only new thing is that for an address without a year, year is undefined, so the component has to handle both cases:

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

function MissionsList() {
  const { year } = useParams();

  return <h2>{year ? `Missions from ${year}` : 'All missions'}</h2>;
}

The component does not know which address it was rendered for, and it does not need to. It receives year or undefined and picks the heading based on that. A static segment, meaning a plain word in the path rather than a parameter, can be optional too:

<Route path="/crew/:memberId/edit?" element={<CrewMember />} />

This route matches both /crew/ra and /crew/ra/edit, and renders the same CrewMember component in both cases.

In versions 6.0 to 6.4 the question mark did not work, so you had to define two separate routes with the same element. This form is still valid and you will come across it in older projects:

<Routes>
  <Route path="/missions" element={<MissionsList />} />
  <Route path="/missions/:year" element={<MissionsList />} />
</Routes>

The third option is query parameters, which are optional by nature. I recommend a simple rule: choose an optional segment when the value builds the address hierarchy, like the year in the mission log, and query parameters when the values are filters that can be combined freely. You will meet query parameters in the next section.

Query Parameters

Query parameters are key-value pairs added after the question mark (?) in the URL. Example: /search?query=mars&category=planets

Accessing Query Parameters with useSearchParams

The useSearchParams hook allows reading and manipulating query parameters:

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

function PlanetSearch() {
  // searchParams is a URLSearchParams object
  // setSearchParams is a function to update the parameters
  const [searchParams, setSearchParams] = useSearchParams();

  // Reading parameter values
  const query = searchParams.get('query') || '';
  const type = searchParams.get('type') || 'all';

  // Function handling the search
  const handleSearch = (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const newQuery = formData.get('searchQuery');
    const newType = formData.get('planetType');

    // Update query parameters
    setSearchParams({ query: newQuery, type: newType });
  };

  return (
    <div className="planet-search">
      <h1>Planet Search Engine</h1>

      <form onSubmit={handleSearch}>
        <input
          name="searchQuery"
          defaultValue={query}
          placeholder="Enter planet name..."
        />

        <select name="planetType" defaultValue={type}>
          <option value="all">All types</option>
          <option value="rocky">Rocky</option>
          <option value="gas-giant">Gas giants</option>
          <option value="ice-giant">Ice giants</option>
        </select>

        <button type="submit">Search</button>
      </form>

      <div className="search-results">
        {/* Search results depending on query and type */}
        <p>Search phrase: {query || '(none)'}</p>
        <p>Planet type: {type}</p>
      </div>
    </div>
  );
}

Manipulating Query Parameters

We can manipulate query parameters in different ways:

// Set new parameters (replaces all existing ones)
setSearchParams({ query: 'mars', type: 'rocky' });

// Add or update a parameter without removing existing ones
setSearchParams(params => {
  params.set('query', 'mars');
  return params;
});

// Remove a parameter
setSearchParams(params => {
  params.delete('type');
  return params;
});

// Check if a parameter exists
const hasType = searchParams.has('type');

// Get all values for a parameter (if it occurs multiple times)
const allCategories = searchParams.getAll('category');

Query Parameters vs. Path Parameters - When to Use Which?

Path Parameters:

  • For identifying the main resource (e.g., /planets/mars)
  • When the parameter is required
  • When the URL structure should reflect the resource hierarchy
  • Examples: planet ID, mission year, constellation name

Query Parameters:

  • For filtering, sorting, pagination
  • For optional parameters
  • When there are many parameter combinations
  • Examples: search criteria, results page, limits, filters

Combining Path and Query Parameters

We can combine both types of parameters for greater flexibility:

// URL: /planets/mars?tab=geology&unit=metric

import { useParams, useSearchParams } from 'react-router-dom';

function PlanetDetails() {
  const { planetId } = useParams();
  const [searchParams] = useSearchParams();

  const activeTab = searchParams.get('tab') || 'overview';
  const unit = searchParams.get('unit') || 'metric';

  return (
    <div>
      <h1>Planet: {planetId}</h1>

      <div className="tabs">
        <TabLink to={`/planets/${planetId}?tab=overview&unit=${unit}`}
          active={activeTab === 'overview'}>
          Overview
        </TabLink>
        <TabLink to={`/planets/${planetId}?tab=geology&unit=${unit}`}
          active={activeTab === 'geology'}>
          Geology
        </TabLink>
        <TabLink to={`/planets/${planetId}?tab=atmosphere&unit=${unit}`}
          active={activeTab === 'atmosphere'}>
          Atmosphere
        </TabLink>
      </div>

      <div className="unit-switcher">
        <UnitToggle
          metric={unit === 'metric'}
          onChange={(isMetric) => {
            const newUnit = isMetric ? 'metric' : 'imperial';
            // Update only the unit parameter, preserve tab
            searchParams.set('unit', newUnit);
            setSearchParams(searchParams);
          }}
        />
      </div>

      {/* Content depending on activeTab and unit */}
    </div>
  );
}

createSearchParams - Simplifying Query Parameter Creation

The createSearchParams function helps create query parameters from JavaScript objects:

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

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

  const applyFilters = (filters) => {
    // Convert filter object to URL parameters
    const params = createSearchParams({
      type: filters.type,
      minSize: filters.minSize,
      hasWater: filters.hasWater ? 'true' : undefined,
      sortBy: filters.sortBy
    });

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

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

When creating links with parameters, we can use:

For path parameters:

// Simple string concatenation
<Link to={`/planets/${planetId}`}>
  Planet details {planetName}
</Link>

// Using an object (more flexible)
<Link to={{
  pathname: `/planets/${planetId}`,
}}>
  Planet details {planetName}
</Link>

For query parameters:

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

// Using createSearchParams
<Link to={{
  pathname: '/planets',
  search: `?${createSearchParams({
    type: 'rocky',
    inhabited: 'true'
  })}`
}}>
  Inhabited rocky planets
</Link>

// Or manually creating parameters
<Link to={`/planets?type=rocky&inhabited=true`}>
  Inhabited rocky planets
</Link>

Full Example Application with URL Parameters

Let's now see a complete space application example using both path parameters and query parameters:

import React, { useState, useEffect } from 'react';
import {
  BrowserRouter,
  Routes,
  Route,
  Link,
  useParams,
  useSearchParams,
  createSearchParams,
  useNavigate
} from 'react-router-dom';

// API simulation
const planetsData = [
  { id: 'mercury', name: 'Mercury', type: 'rocky', diameter: 4879, hasWater: false },
  { id: 'venus', name: 'Venus', type: 'rocky', diameter: 12104, hasWater: false },
  { id: 'earth', name: 'Earth', type: 'rocky', diameter: 12742, hasWater: true },
  { id: 'mars', name: 'Mars', type: 'rocky', diameter: 6779, hasWater: true },
  { id: 'jupiter', name: 'Jupiter', type: 'gas-giant', diameter: 139820, hasWater: true },
  { id: 'saturn', name: 'Saturn', type: 'gas-giant', diameter: 116460, hasWater: true },
  { id: 'uranus', name: 'Uranus', type: 'ice-giant', diameter: 50724, hasWater: true },
  { id: 'neptune', name: 'Neptune', type: 'ice-giant', diameter: 49244, hasWater: true },
];

// Main components
function PlanetsList() {
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();

  // Read query parameters
  const type = searchParams.get('type') || 'all';
  const hasWater = searchParams.get('hasWater');
  const sortBy = searchParams.get('sortBy') || 'name';

  // Filter planets
  const filteredPlanets = planetsData
    .filter(planet => type === 'all' || planet.type === type)
    .filter(planet => hasWater === null || (hasWater === 'true' && planet.hasWater))
    .sort((a, b) => {
      if (sortBy === 'name') return a.name.localeCompare(b.name);
      if (sortBy === 'diameter') return b.diameter - a.diameter;
      return 0;
    });

  // Function to update filters
  const updateFilters = (newFilters) => {
    const params = createSearchParams({
      ...Object.fromEntries(searchParams),
      ...newFilters
    });
    setSearchParams(params);
  };

  return (
    <div className="planets-list">
      <h1>Planet Catalog</h1>

      <div className="filters">
        <label>
          Planet type:
          <select
            value={type}
            onChange={(e) => updateFilters({ type: e.target.value })}
          >
            <option value="all">All</option>
            <option value="rocky">Rocky</option>
            <option value="gas-giant">Gas giants</option>
            <option value="ice-giant">Ice giants</option>
          </select>
        </label>

        <label>
          <input
            type="checkbox"
            checked={hasWater === 'true'}
            onChange={(e) => updateFilters({ hasWater: e.target.checked ? 'true' : null })}
          />
          With water only
        </label>

        <label>
          Sort by:
          <select
            value={sortBy}
            onChange={(e) => updateFilters({ sortBy: e.target.value })}
          >
            <option value="name">Name</option>
            <option value="diameter">Size</option>
          </select>
        </label>
      </div>

      <ul className="planets-grid">
        {filteredPlanets.map(planet => (
          <li key={planet.id} className={`planet ${planet.type}`}>
            <Link to={`/planets/${planet.id}`}>
              <h2>{planet.name}</h2>
              <p>Type: {planet.type}</p>
              <p>Diameter: {planet.diameter} km</p>
              <p>Water: {planet.hasWater ? 'Present' : 'Absent'}</p>
            </Link>
          </li>
        ))}
      </ul>

      {filteredPlanets.length === 0 && (
        <p>No planets found matching the criteria.</p>
      )}

      <button onClick={() => navigate('/')}>
        Return to control center
      </button>
    </div>
  );
}

function PlanetDetails() {
  const { planetId } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();

  // Read query parameters
  const activeTab = searchParams.get('tab') || 'overview';

  // Find planet with given ID
  const planet = planetsData.find(p => p.id === planetId);

  // If planet not found
  if (!planet) {
    return (
      <div className="planet-not-found">
        <h1>Planet does not exist!</h1>
        <p>No planet found with identifier: {planetId}</p>
        <button onClick={() => navigate('/planets')}>
          Return to planet catalog
        </button>
      </div>
    );
  }

  // Change active tab
  const changeTab = (tab) => {
    setSearchParams({ tab });
  };

  return (
    <div className="planet-details">
      <h1>{planet.name}</h1>

      <div className="tabs">
        <button
          className={activeTab === 'overview' ? 'active' : ''}
          onClick={() => changeTab('overview')}
        >
          Overview
        </button>
        <button
          className={activeTab === 'composition' ? 'active' : ''}
          onClick={() => changeTab('composition')}
        >
          Composition
        </button>
        <button
          className={activeTab === 'exploration' ? 'active' : ''}
          onClick={() => changeTab('exploration')}
        >
          Exploration
        </button>
      </div>

      <div className="tab-content">
        {activeTab === 'overview' && (
          <div>
            <h2>Overview of planet {planet.name}</h2>
            <p>Type: {planet.type}</p>
            <p>Diameter: {planet.diameter} km</p>
            <p>Water: {planet.hasWater ? 'Present' : 'Absent'}</p>
          </div>
        )}

        {activeTab === 'composition' && (
          <div>
            <h2>Composition of planet {planet.name}</h2>
            <p>Information about planet composition will appear here...</p>
          </div>
        )}

        {activeTab === 'exploration' && (
          <div>
            <h2>Exploration of planet {planet.name}</h2>
            <p>Information about exploration missions will appear here...</p>
          </div>
        )}
      </div>

      <Link to="/planets">Return to planet catalog</Link>
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      <div className="space-app">
        <header>
          <h1>Cosmic Navigation System</h1>
        </header>

        <main>
          <Routes>
            <Route path="/" element={<Dashboard />} />
            <Route path="/planets" element={<PlanetsList />} />
            <Route path="/planets/:planetId" element={<PlanetDetails />} />
            <Route path="*" element={<NotFound />} />
          </Routes>
        </main>

        <footer>
          <p>&copy; 2150 Interplanetary Space Agency</p>
        </footer>
      </div>
    </BrowserRouter>
  );
}

// Other components
function Dashboard() {
  return (
    <div className="dashboard">
      <h1>Mission Control Center</h1>
      <p>Welcome to the cosmic navigation system!</p>
      <Link to="/planets">Browse planet catalog</Link>
    </div>
  );
}

function NotFound() {
  return (
    <div className="not-found">
      <h1>Navigation Error: 404</h1>
      <p>Lost in space! This page does not exist.</p>
      <Link to="/">Return to Control Center</Link>
    </div>
  );
}

export default App;

Best Practices for URL Parameters

  1. Use readable parameter names - they should describe what they represent
  2. Choose the appropriate type of parameters - path parameters for main resources, query parameters for filters
  3. Handle missing parameters - always provide default values
  4. Validate parameters - check if values are correct before using them
  5. Preserve query parameter state - update only the parameters that change
  6. Use parameters to store UI state - this makes it easier to share and save state

Summary

URL parameters are a powerful tool in cosmic navigation (and React Router). They allow for:

  • Identifying specific resources (path parameters)
  • Filtering and sorting data (query parameters)
  • Remembering the user interface state
  • Creating shareable and bookmarkable links
  • Handling browser history

Thanks to them, users can precisely navigate to specific locations in the space application, and you as a programmer can create interactive and user-friendly interfaces.

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

// Planet list
const planets = [
  { id: 'mars', name: 'Mars', emoji: '', distance: '225M km' },
  { id: 'jupiter', name: 'Jupiter', emoji: '', distance: '628M km' },
  { id: 'saturn', name: 'Saturn', emoji: '', distance: '1.2B km' },
  { id: 'neptune', name: 'Neptune', emoji: '', distance: '4.3B km' },
];

// Home page with planet list
function PlanetList() {
  return (
    <div className="planet-list">
      <h1>Planet Catalog</h1>
      <div className="planets-grid">
        {planets.map(planet => (
          <Link
            key={planet.id}
            to={`/planet/${planet.id}`}
            className="planet-card"
          >
            <div className="planet-emoji">{planet.emoji}</div>
            <h3>{planet.name}</h3>
            <p>{planet.distance}</p>
          </Link>
        ))}
      </div>
    </div>
  );
}

// Planet details - using useParams
function PlanetDetails() {
  const { planetId } = useParams();
  const planet = planets.find(p => p.id === planetId);

  if (!planet) {
    return (
      <div className="not-found">
        <h1>Planet not found</h1>
        <p>No planet found with ID: {planetId}</p>
        <Link to="/" className="back-link">โ† Back to catalog</Link>
      </div>
    );
  }

  return (
    <div className="planet-details">
      <Link to="/" className="back-link">โ† Back to catalog</Link>
      <div className="planet-hero">
        <div className="planet-emoji-large">{planet.emoji}</div>
        <h1>{planet.name}</h1>
      </div>
      <div className="planet-info">
        <div className="info-item">
          <span className="label">ID:</span>
          <span className="value">{planet.id}</span>
        </div>
        <div className="info-item">
          <span className="label">Distance from Earth:</span>
          <span className="value">{planet.distance}</span>
        </div>
        <div className="info-item">
          <span className="label">URL parameter:</span>
          <span className="value code">:planetId = "{planetId}"</span>
        </div>
      </div>
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      <div className="app">
        <Routes>
          <Route path="/" element={<PlanetList />} />
          <Route path="/planet/:planetId" element={<PlanetDetails />} />
        </Routes>
      </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 key difference between the Link and NavLink components?

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the Route syntax elements in React Router v6:

  • Code editor

    Dynamic URL parameters

  • Vertical ordering

    Arrange the routing hierarchy in a space application:

  1. Put in orderRoutes Configuration
  2. QuestionLink vs NavLink
  3. Coding taskPractice: Link and NavLink
  4. Put in orderCosmic routing hierarchy

Useful articles