React routing
Created on: Sep 19, 2024
React Router is a popular library for managing client-side routing in React applications. It allows you to create complex, multi-page web applications that feel like traditional websites while still being single-page applications (SPAs) under the hood.
import { BrowserRouter, Routes, Route, createBrowserRouter, } from "react-router-dom"; import NavBar from "./component/NavBar"; import Home from "./component/Home"; import ContactUs from "./component/ContactUs"; import NoPageFound from "./component/NoPageFound"; import AboutUs from "./component/AboutUs"; import { Link } from "react-router-dom"; import CourseDetails from "./component/CourseDetails"; export default function Router1() { const courses = ["JavaScript", "React", "HTML", "DSA"]; return ( <div className="App"> <BrowserRouter> <NavBar /> <Routes> <Route exact path="/" element={<Home />} /> <Route exact path="/about" element={<AboutUs />} /> <Route exact path="/contact" element={<ContactUs />} /> <Route path="*" element={<NoPageFound />} /> </Routes> </BrowserRouter> {/* Dynamic routing */} <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> </div> ); }
We can also use createBrowserRouter to create routes, which provides more options and flexibility for route configuration.
import Root from "./component/Root"; import ErrorPage from "./component/ErrorPage"; import { createBrowserRouter } from "react-router-dom"; const Router2 = createBrowserRouter([ { path: "/root", element: <Root />, errorElement: <ErrorPage />, }, ]); export default Router2;
Comparison:
| Feature | BrowserRouter | createBrowserRouter |
|---|---|---|
| Version | React Router v5 and React Router v6 (basic usage) | React Router v6.4+ (data-driven) |
| Routing Setup | Defined inside JSX using <Route> components | Defined outside JSX in a routing configuration |
| Data Fetching | Requires separate logic (e.g., useEffect) | Built-in data loading capabilities |
| Error Handling | Done manually within components | Automatic error boundaries per route |
| Nested Routes | Supported but requires manual handling | Simplified and supported natively |
Which is Better?
- Use
BrowserRouterif you prefer a simpler, more traditional approach to routing, where the routing configuration is embedded within your components. It's easy for small to medium-sized applications. - Use
createBrowserRouterif you want a more structured, data-driven routing system. It's better for larger apps that need features like automatic data loading, nested routes, and error handling.
Checkout my whole code in github
