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