Dynamic Routing with React router

Adding Link routes gets very lengthy when there are multiple pages, so we use the concept of Dynamic Routing to reduce the lines of code and make the code shorter

Approach:

  • Create a page which will create Link components using map
  • Create a page which will display data dynamically using useParams
  • Create a dynamic Route component which passes the id as a parameter

Example: Write the following code in respective files after removing default styling in App.css

  • App.js: This file creates Link component dynamically and sends course name as a parameter
  • CourseDetails.js: This file accesses the course as a parameter and passes it.

Javascript




// App.js
  
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
import CourseDetails from "./components/CourseDetails";
  
function App() {
    const courses = ["JavaScript", "React", "HTML", "DSA"];
    return (
        <BrowserRouter>
            <h1>Dynamic Routing with React</h1>
            <ul>
                {courses.map((course) => {
                    return (
                        <li key={course}>
                            <Link to={`courses/${course}`}>{course}</Link>
                        </li>
                    );
                })}
            </ul>
            <Routes>
                <Route path="courses/:courseId" element={<CourseDetails />} />
            </Routes>
        </BrowserRouter>
    );
}
  
export default App;


Javascript




// components/CourseDetails.js
  
import { useParams } from "react-router-dom";
  
function CourseDetails() {
    const { courseId } = useParams();
    return (
        <div>
            <h1>This is {courseId} course</h1>
        </div>
    );
}
  
export default CourseDetails;


Output:



Mastering React Routing: Learn Navigation and Routing in React Apps

In this article, we will learn how to implement Routing in React in an efficient way by implementing various aspects of routing such as dynamic routing, programmatically routing, and other concepts.

Table of Content

  • What is Navigation in React?
  • Routing with no page found(error 404) error handling
  • Programmatic Navigation in React
  • Dynamic Routing with React router

Similar Reads

What is Navigation in React?

...

Routing with no page found(error 404) error handling

Navigation means browsing between various parts of the application. In React mostly SPA(Single Page Application) are developed so Navigation is complex. We do not load new pages from the server side each time a navigation link is pressed instead routing is implemented on the client side....

Programmatic Navigation in React

Sometimes user types a URL which does not exist in the website and the router fails and shows an error. To solve this problem we create a universal Route component which redirects to Link not found page whenever incorrect URL is passed...

Dynamic Routing with React router

...