React Router
React by default doesn't come with routing capabilities — that’s where React Router comes in. It’s the standard library for handling navigation in React applications. In this tutorial, we’ll set up multiple page routes using React Router v6.
Installing React Router
To get started, install React Router DOM by running:
Folder Structure
Each file will contain a basic React component representing a page.
Creating Page Components
Here are the components for each route:
Layout.js
Home.js
Blogs.js
Setting Up Routing in index.js
We define routes using the <Routes>
and <Route>
components.
index.js
Understanding the Routing Logic
<BrowserRouter>
wraps the whole application to enable routing.<Routes>
is the container for all your routes.<Route path="/" element={<Layout />}>
sets up the main layout route.<Route index element={<Home />}>
means this is the default child route (/).<Route path="blogs" element={<Blogs />}>
maps to /blogs.<Route path="*" element={<NoPage />}>
is the catch-all for unknown URLs (404 page).
Using Link and Outlet
<Link>
is used instead of<a>
to enable client-side navigation without reloading the page.<Outlet>
is a placeholder for where the nested route components should render.
Summary
- React Router is a routing library for React apps.
- Use it to navigate between pages without refreshing the browser.
- Organize your app using nested routes and layout components.
- Replace
<a>
with<Link>
for internal navigation.