Routing and Using React Router

killerkvothe117

Kosi Iyiegbu

Posted on June 20, 2022

Routing and Using React Router

Routing is the ability to move between different parts of an application when a user enters a URL or clicks an element(link, button, icon, etc.) within the application. To add routing in our react applications we need to install a library called react-router.

React Router is a standard library used for routing in React. It helps developers create single-page applications that are responsive and have a dynamic user-interface. React Router makes it easy to build apps that work well on both desktop or mobile, regardless of where users are browsing from.

To install the react-router in your react application, you have to run the following command in the terminal depending on your packet manager.

$ npm install react-router-dom@6
Enter fullscreen mode Exit fullscreen mode

Or

$ yarn add react-router-dom@6
Enter fullscreen mode Exit fullscreen mode

This will install the latest version which is version 6.

React Router comes with some Components, Hooks, etc. We'll look at some of them and how they're used.

<BrowserRouter>:

The <BrowserRouter /> serves as a parent component used to store all other components. It stores the current location in the browser's address bar using clean URLs and navigates using the browser's built-in history stack.

import React "react";
import { BrowserRouter } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      {/* The rest of your components will go into this space */}
    </BrowserRouter>
 );
}
Enter fullscreen mode Exit fullscreen mode

In the code above you can see how the <BrowserRouter /> serves as the parent component that wraps all other components for your application.

<Routes> and <Router>:

<Routes> and <Route> are the primary ways to render something in React Router based on the current location. All <Route> components are wrapped inside the <Routes>. If the "path" of a <Route> matches the current URL, it will render its element.
The "path" of a <Route> is an attribute that specifies the URL of the desired component. Any component whose pathname is a backslash will get rendered first whenever the app loads for the first time. This implies that the "Home" component will be the first component to get rendered.
The second attribute called "element" specifies the component the should render.

Whenever the location changes, <Routes> looks through all the children <Route> elements to find the best match and renders that branch of the UI.

import { BrowserRouter, Routes, Route } from "react-router-dom"
import Home from "./Home"
import About from "./About"
import Profile from "./Contact"

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={ <Home /> } />
        <Route path="/about" element={ <About /> } />
        <Route path="/profile" element={ <Profile /> } />
      </Routes>
    </BrowserRouter>
  );
}

export default App
Enter fullscreen mode Exit fullscreen mode

<Link>:

This is an element that lets the user navigate to another page by clicking or tapping on it without having to reload the page. It is similar to the anchor element (<a>) in HTML. It's "to" attribute specifies the path that the link takes you to.

import React from "react";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import Home from "./Pages/Home";
import About from "./Pages/About";
import Profile from "./Pages/Profile";

export default function App() {
  return (
   <Router>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/profile">Profile</Link></li>
        </ul>
      </nav>

    <Routes>
     <Route path="/" element={ <Home /> } />
     <Route path="/about"  element={ <About /> } />
     <Route path="/profile"  element={ <Profile /> } />
    </Routes>
  </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

<NavLink>:

This is a special kind of <Link> that knows whether or not it is active. It is useful when building a navigation menu where you would want to show which of them is currently selected.

By default, an "active" is added to the <NavLink> component when it is active which provides a simple styling mechanism for users. You can pass a function the the "style" or "className" attributes that will allow you to customize the inline styling or class based on the components active state. The code below shows how it would work:

import React from "react";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import Home from "./Pages/Home";
import About from "./Pages/About";
import Profile from "./Pages/Profile";

export default function App() {
  return (
   <Router>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li>
            <NavLink  style={({ isActive }) => (isActive ? { 
            color: "red" } : undefined)}
            to="/about">
             About
            </NavLink>
          </li>
          <li><Link to="/profile">Profile</Link></li>
        </ul>
      </nav>

    <Routes>
     <Route path="/" element={ <Home /> } />
     <Route path="/about"  element={ <About /> } />
     <Route path="/profile"  element={ <Profile /> } />
    </Routes>
  </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

When the code above is rendered, The <NavLink> would have a color of red when it is active.

useNavigate:

This is a hook that returns a function to let you navigate programmatically, for example after a form submission. It can be used to redirect a user to a specific URL and can also be used to go to the previous or next page. If using "replace: true", the navigation will replace the current entry in the history stack instead of adding a new one. It can also accept a 2nd optional argument which is "state" and we can use this to pass values to another component.

import React from "react";
import { useNavigate } from "react-router-dom";

function Profile() {
  let navigate = useNavigate();
  return (
    <div>
      THIS IS THE PROFILE PAGE
      <button
        onClick={() => {
          navigate("/about");
        }}
      >
        Change to about page
      </button>
    </div>
  );
}

export default Profile;
Enter fullscreen mode Exit fullscreen mode

The code above is one of the use cases of the navigate function. We can also pass in numbers like this: navigate(1) or navigate(-1) which would take you to the next page or previous page respectively.

useParams:

The useParams hook helps us to get the parameter passed on the URL without using the props object. It returns an object of key/value pair of the dynamic params from the URL that was matched by the <Route path>.

import React from 'react';
import { BrowserRouter as Router, Routes, Route, useParams } from 'react-router-dom';

function ProfilePage() {
  // Get the userId param from the URL.
  let { userId } = useParams();
  // ...
}

function App() {
  return (
  <Router>
    <Routes>
        <Route path="/" element={ <Welcome /> } />
        <Route path="/profile/:userId" element={ <Profile /> } />
        <Route path="/services" element={ <Services /> } />
    </Routes>
  </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

useLocation:

This hook returns the current location object. The object represents the current URL and it is immutable. This can be useful if you'd like to perform some side effect whenever the current location changes. Some of its use includes extracting the query parameters from the URL and doing something depending on the query parameters. The “search” property of the location object returns a string containing the query part of the URL.

import React from "react";
import { BrowserRouter as Router, Routes, Route useLocation } from "react-router-dom";

export default function App() {
  const location = useLocation();
  useEffect(() => {
    console.log(location.pathname);
  }, [location]);

  return (
    <Router>
      <Routes>
        <Route path="/" element={ <Home /> } />
        <Route path="/about"  element={ <About /> } />
        <Route path="/profile"  element={ <Profile /> } />
      </Routes>
    </Router>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the code above, the "pathname" contains the user's current location and it would change depending on the current <Route path>.

Conclusion

So far, React Router v6 is very promising. The new features and Hooks will definitely encourage cleaner code. I hope you enjoyed this article and found it useful!

💖 💪 🙅 🚩
killerkvothe117
Kosi Iyiegbu

Posted on June 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related