Routing

Routing in React works by mapping URLs to components, allowing users to navigate through different parts of a single-page application without refreshing the entire page.

Page Layout

Untitled

<aside> 💡 Before setting up routing in a React app, design the overall page layout to organize the main structure, like headers, footers, and navigation bars.

</aside>

Steps For Routing

  1. Install react-router-dom

    npm install react-router-dom
    
  2. Create Route Components

    Layout.jsx

    import Footer from "./Footer";
    import Navbar from "./Navbar";
    import { Outlet } from "react-router-dom";
    
    function Layout(){
        return(
            <div>
                <Navbar/>
                {/* Add Dynamic Content Here */}
                <div style={{minHeight:'100vh'}}>
                    <Outlet/>
                </div>
                <Footer/>
            </div>
        )
    }
    
    export default Layout;
    
  3. Import Routing → BrowserRouter

    Home v6.23.1

  4. Set Up Router in App Component

    import { Children } from 'react';
    import Layout from './Layout';
    import {createBrowserRouter,RouterProvider} from 'react-router-dom'
    import Register from './Register';
    import Login from './Login';
    import Home from './Home';
    
    function App(){
    
      //  Create Browser Router object
      const browserRouter = createBrowserRouter([
        {
          path:'',
          element:<Layout/>,
          children:[
          {
            path:'',
            element:<Home/>
          },
          {
            path:'register',
            element:<Register/>
          },
          {
            path:'login',
            element:<Login/>
    
          }]
        },
      ]);
      return (
        <RouterProvider router={browserRouter}>
          {Children}
        </RouterProvider>
      )
    }
    export default App;
    
  5. Setup links in the Navbar

    import { Link } from "react-router-dom";
    function Navbar(){
        return(
            <div>
                <ul className='nav fs-4 justify-content-end bg-secondary'>
                    <li className='nav-item'>
                        <Link to="" className='nav-link text-white'>Home</Link>
                    </li>
                    <li className='nav-item'>
                        <Link to="register" className='nav-link text-white'>Register</Link>
                    </li>
                    <li className='nav-item'>
                        <Link to="login" className='nav-link text-white'>Login</Link>
                    </li>
                </ul>
            </div>
        )
    }
    
    export default Navbar;
    

Website

https://reactjs-routing.netlify.app/


Dynamic Routes

Steps for Creating Dynamic Routes

  1. Install react-router-dom

    npm install react-router-dom