Creating Routes Using React Router DOM

PrincePrince
2 min read

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:

  1. What?

  2. Why?

  3. 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 :-

    1. Client-Side Routing

    2. Seamless Navigation

    3. Declarative Routing

    4. Nested Routing

    5. Route Gaurds

HOW ?

  1. Install the library

    npm install react-router-dom

  2. Setting Up Browser Router - wrap your root component with BrowserRouter

    <BrowserRouter> <App /> </BrowserRouter>

  3. 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 />,
           },
         ],
       },
     ]);
    
0
Subscribe to my newsletter

Read articles from Prince directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prince
Prince