React Router DOM Simplified – From Setup to Dynamic Routes

React Router DOM is a routing library for React applications that allows you to define navigation routes and render components based on the current URL. It's a powerful tool for creating dynamic and user-friendly single-page applications (SPAs).
Installation
To get started, install React Router DOM using npm or yarn:
npm install react-router-dom
Link & NavLink
Once installed, you can use the Link and NavLink components to create navigation links within your application. These components allow users to navigate between different routes without reloading the page.
import { Link, NavLink } from 'react-router-dom';
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<NavLink to="/contact" className={({ isActive }) => `${isActive ? "text-orange-700" : "text-gray-700"}`>Contact</NavLink>
</nav>
Layout
The Layout component is a higher-order component (HOC) that provides a common layout for your application's pages. It's useful for defining reusable components like headers, footers, and sidebars.
import { Layout } from 'react-router-dom';
<Layout>
<Header />
<Outlet />
<Footer />
</Layout>
<Outlet> is a special component provided by React Router Dom. It serves as a placed between the Header and Footer components within the Layout component. where the content of the currently matched route will be rendered.
CreateBrowserRouter() Method
The createBrowserRouter() function is the core of React Router DOM. It takes an array of routes as an argument and returns a router object. Each route defines a path, an element to render, and optionally, child routes.
import { createBrowserRouter } from 'react-router-dom';
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{ path: "/", element: <Home /> },
{ path: "/about", element: <About /> },
{ path: "/contact", element: <Contact /> },
{ path: "/user/:userId", element: <User /> },
],
},
]);
Rendering the Router
To render the router in your application, use the RouterProvider component and pass it to the router object created using createBrowserRouter().
import ReactDOM from 'react-dom';
import React from 'react';
import { RouterProvider } from 'react-router-dom';
const router = createBrowserRouter([
// ... routes
]);
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
This will make the router available throughout your application, allowing you to use the Link and NavLink components to navigate between routes.
Conclusion
React Router DOM is a powerful and versatile routing library for React applications. It provides a simple and declarative way to define navigation routes and create dynamic SPAs. By following the steps outlined in this guide, you can easily integrate React Router DOM into your React projects and enhance the user experience of your web applications.




