A Super Short BASIC Guide on Implementing Browser Router in your React Application

React Router 6 that is!

A Super Short BASIC Guide on Implementing Browser Router in your React Application

1. First Install react-router-dom

npm i react-router-dom

2. Import the necessary modules

//App.js
import { Routes, Route, BrowserRouter as Router } from 'react-router-dom';

3. Wrap every component that needs routing in a single Router component

//... Main App
  return (
    <Router>
      <MyComponentA />
      <MyComponentB />
      <MyComponentC />
    </Router>
  );

4. Now Wrap them in a single Routes component

  return (
    <Router>
     <Routes>
        <MyComponentA />
        <MyComponentB />
        <MyComponentC />
      </Routes>
    </Router>
  );

5. For each specific route, create a Route component inside the Routes component

  return (
    <Router>
      <Routes>
        <Route exact path="/AandB" />
        <Route path="/C" />
        <MyComponentA />
        <MyComponentB />
        <MyComponentC />
      </Routes>
    </Router>
  );

6. For each Route component, add an element attribute and move the components into the attribute

Take Note this is written in JSX so for multiple components, you will need a parent element or fragment

  return (
    <Router>
      <Routes>
        <Route
          exact
          path="/AandB"
          element={
            <>
              <MyComponentA />
              <MyComponentB />
            </>
          }
        />
        <Route path="/C" element={<MyComponentC />} />
      </Routes>
    </Router>
  );

Extras


Links in React and anchor tags have similar functionality, but there are some key differences between them:

Syntax: In React, you create a link using the component from the react-router-dom library, while in HTML, you use the tag.

Routing: The component in React allows you to manage routing within your application, while anchor tags will cause the page to reload and navigate to the specified URL.

Dynamic behavior: With the component, you can dynamically update the destination of the link based on the state of your application, while anchor tags always navigate to the same URL.

Integration with React: The component integrates seamlessly with React, allowing you to use it as part of your component-based architecture, while anchor tags are part of the HTML markup.

In summary, while both links in React and anchor tags allow you to create links to other pages, the component provides additional functionality for managing routing within your React application and integrating with the React framework.

<a href ='/about'> About Page </a>

//becomes

import {Link} from react-router-dom;

<Link to='/about'> About Page </Link>

NavLinks has a prop called activeClassName that allows you to highlight the link you are currently on.

        <NavLink to="/" activeClassName="highlight">
          Home
        </NavLink>

        <NavLink to="/about" activeClassName="highlight">
          About
        </NavLink>

Getting the Params from a URL requires a hook called useParams provided by react-router-dom.

//main app

<Route path="/post/:id/:name" element={<Post/>} />

//post component
import { useParams  } from "react-router-dom";
function Post() {
  const params = useParams();
  return (
    <div>
    <p>Post Id: {params.id}</p>
    <p>Written By: {params.name}</p>
    </div>
  )
}

Assuming the link is localhost:3000/post/376/William

The result would show:

Post Id: 376

Written By: William

9. Navigation and Nested Routes

To navigate(redirect) to different parts of the app depends on the situation.

First, we can use Navigate

import { Navigate } from "react-router-dom";
function Post() {
const status = getStatus();
if(status ====404){
  return <Navigate to='/NotFound>'/>
}

  return (
    <div>
    <h1>Posts</h1>

    </div>
  )
}

Alternatively, you can use useNavigate

import { Navigate, useNavigate } from "react-router-dom";


function Post() {

  const navigate = useNavigate();

  const handleClick = ()=>{
    //do something then redirect

  navigate('/login')
  }


  return (
    <div>
    <h1>Posts</h1>
    <Button onClick={handleClick}> </Button>

    </div>
  )
}

useNavigate is a hook that provides access to the navigate method within functional components, whereas navigate is the method directly provided by the react-router-dom library that can be used in any context.

Let's assume we want the Post component to have a nested route /badge, which resolves to /post/badge to reveal a Badge component.

To get nested routes, add the Routes and Route imports from react-router-dom in the chosen component (Post) and add the Routes and Route components as required then add the nested component in the element prop of the Route component (<BadgeComponent/>)

However, for this to work, the route that is responsible for navigating to post in the main component must have a forward slash and an asterisk (/*) after the path. Visually it looks like this:


┌─────────────────────┐
│Main App Component   │    The Component that
│<Route path="/post/*"│    Routes to post must
│ element={<Post/>} />│    append "/*" to path
└─────────┬───────────┘    for Badge to render
          │               ┌─────────────────────┐
          │               │Post Copmponent      │
          └─────────────► │<Route path="/badge" │
                          │element={<Badge/>} />│
                          │                     │
                          └──────────┬──────────┘
                                     │
  Badge component                    │
  nested in Post                     ▼
  component                 ┌────────────────┐
                            │Badge Component │
localhost:3000/post/badge/  └────────────────┘

The code looks like this:


//Main App
...
    <Route path="/post/*" element={<Post />} />


//Post Component
import { Routes, Route, } from "react-router-dom";
function Post() {

  return (
    <div>
    <h1>Posts</h1>
    <Routes>
      <Route path='/badge' element={<BadgeComponent/>}>

      </Route>
    </Routes>

    </div>
  )
}

If you go to localhost:3000/post/badge you will see the Badge component. The Badge component will not be displayed on /post and will not work if you omit the trailing /* in the Post component's route path in the main App (parent component).