Menu

Dynamic Routes and URL Parameters

Dynamic Routes and URL Parameters

What is a Dynamic Route?

You cannot write a separate route for every course. Instead, you define one route with a placeholder segment and read the actual value from the URL.

Syntax

jsx

<Route path="/courses/:courseId" element={<CourseDetails />} />

The :courseId part matches any value and makes it available to the component.

Example

src/pages/Courses.jsx

jsx

import { Link } from "react-router-dom";

function Courses() {
  const courses = [
    { id: 1, title: "React Fundamentals" },
    { id: 2, title: "Node.js Basics" },
    { id: 3, title: "MongoDB Essentials" }
  ];

  return (
    <div>
      <h1>All Courses</h1>
      <ul>
        {courses.map(course => (
          <li key={course.id}>
            <Link to={`/courses/${course.id}`}>{course.title}</Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default Courses;
src/pages/CourseDetails.jsx
jsx
import { useParams, Link } from "react-router-dom";

function CourseDetails() {
  const { courseId } = useParams();

  const courses = {
    1: { title: "React Fundamentals", lessons: 12, level: "Beginner" },
    2: { title: "Node.js Basics", lessons: 18, level: "Intermediate" },
    3: { title: "MongoDB Essentials", lessons: 9, level: "Beginner" }
  };

  const course = courses[courseId];

  if (!course) {
    return (
      <div>
        <p>Course not found.</p>
        <Link to="/courses">Back to all courses</Link>
      </div>
    );
  }

  return (
    <div>
      <h1>{course.title}</h1>
      <p>{course.lessons} lessons · {course.level}</p>
      <Link to="/courses">Back to all courses</Link>
    </div>
  );
}

export default CourseDetails;

How It Works

  • <Link to={`/courses/${course.id}`}> builds the URL using a template literal.
  • const { courseId } = useParams(); reads the value from the URL. The key name must match the :courseId in the route definition.
  • URL parameters are always strings. courseId is "1", not 1. If you need a number, use Number(courseId).
  • The "not found" check handles someone typing an invalid ID directly into the address bar. Always handle it.

Output

Clicking a course in the list navigates to /courses/1 and shows that course's details. The URL is shareable and the back button works.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details