Creating Routes Using React Router DOM
To create a Multi-Page Application, we need to use routes that allow users to navigate between different pages of the website without refreshing the entire application. For this, we will use a popular library called react-router-dom.
Now we will divide this blog into three parts:
What?
Why?
How?
What ?
React Router DOM is a library used for routing in React applications. It enables developers to create navigation between different components and manage URLs efficiently. It provides a set of components like
BrowserRouter
,Routes
,Route
,Link
, and more to facilitate client-side routing.Why?
Using React Router DOM makes it easier to create a Multi-Page Application in React. It lets users move between different pages without refreshing the whole app, giving a smoother and faster user experience. It also helps manage URLs effectively, making your application more organized and easier to maintain.. ?
It offers several benefits, making it essential for creating seamless, single-page-applications.
Key Reasons :-
Client-Side Routing
Seamless Navigation
Declarative Routing
Nested Routing
Route Gaurds
HOW ?
Install the library
npm install react-router-dom
Setting Up Browser Router - wrap your root component with BrowserRouter
<BrowserRouter> <App /> </BrowserRouter>
Create Routes
1st method :-
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
2nd method :-
const router = createBrowserRouter([ { path: "/", element: <Layout />, children: [ { path: "", element: <Home />, }, { path: "about", element: <About />, }, { path: "contact", element: <Contact />, }, ], }, ]);
Subscribe to my newsletter
Read articles from Prince directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by