DEV Community

Cover image for React Router: A comprehensive guide for beginners
Martin Wachira
Martin Wachira

Posted on

React Router: A comprehensive guide for beginners

React router, is a routing library that helps you create dynamic and responsive single-page applications with different views and pages that update without reloading the entire application.

In this article, we will discuss how to use react router and show an example of how to use it in a React application.

Table of contents
Installing react router
Configuring the router
Defining routes
Handling navigation with Link and NavLink
Link
NavLnk
Dynamic routing

Installing React Router
To install the library, we can use the npm package manager by running the following command:

 npm i react-router-dom
Enter fullscreen mode Exit fullscreen mode

Configuring the Router
To configure our router, we will wrap our root component in BrowserRouter.

import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

Browser router, is a component provided by the React Router that enables client-side routing in a single-page application.

It works by synchronizing the URL in the browser's address bar with the components displayed on the screen.

Defining routes
Defining routes is mostly done at the top most level of your application, such as the app.js.

import "./App.css";
import { Routes, Route } from "react-router-dom";
import HomePage from './pages/HomePage'
import Images from './pages/Images'
import PageNotFound from './pages/PageNotFound'

function App() {
  return (
    <div className="App">

      <Routes>
        <Route path="/" element={<HomePage />} />        {/* It maps the path "/" to the <HomePage /> component, which will be rendered when the user navigates to the root path. */}

        <Route path="/images" element={<Images />} />
        {/*  This line defines a route for the "/images" path of the application. */}
        <Route path="*" element={<PageNotFound />} />
        {/* It maps any other path to the <PageNotFound/> component, which will be rendered when the user navigates to any undefined path. */}
      </Routes>

    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Code explanation

<Routes>:
This is a parent component that defines the routes for the web application.

<Route path="/" element={ <HomePage/> } />: 
It maps the path "/" to the <HomePage/> component, which will be rendered when the user navigates to the root path.

<Route path="/images" element={ <Images/> } />: 
This line defines a route for the "/images" path of the application.

<Route path="*" element={ <PageNotFound/> } />: 
This line defines a fallback route for any other paths that are not defined in the previous routes.

It maps any other path to the <PageNotFound/> component, which will be rendered when the user navigates to any undefined path.`
Enter fullscreen mode Exit fullscreen mode

Handling navigation
Using the Link component
React router uses a Link component which is used to create a hyperlink that allows users to navigate to a different route or page within a React application without having to reload the entire page.

import React from 'react'
import { Link } from 'react-router-dom'

function NavBar() {
   return (
     <nav className='navBar'>
        <ul>
           <li><Link to='/'>Home</Link></li>
           <li><Link to='/images'>Images</Link></li>
           <li><Link to='/pagenotfound'>Page not found!!</Link></li>
        </ul>
     </nav>
    )
}


export default NavBar
Enter fullscreen mode Exit fullscreen mode

When a user clicks on a Link component, React Router will update the URL in the browser's address bar to match the path specified in the to prop of the Link.
This will trigger React Router to render the component associated with that path.

Using NavLink
In React Router, you can also use the NavLink component to create links that have additional styling when they match the current URL.

The NavLink component is similar to the Link component, but it provides additional props that allow you to customize the styling of the link based on whether or not it matches the current URL.

import React from 'react'
import { NavLink } from 'react-router-dom'
import { Link } from 'react-router-dom'
function NavBar() {
   return (
     <nav className='navBar'>
        <ul>
         <li><NavLink to='/' className={'activeLink'}>Home</NavLink></li>
         <li><NavLink to='/images' className={'activeLink'}>Images</NavLink></li>
          <li><NavLink to='/pagenotfound' className={'activeLink'}>Page not found!!</NavLink></li>
        </ul>
     </nav>
   )
}

export default NavBar
Enter fullscreen mode Exit fullscreen mode

The activeLink prop allows you to specify a CSS class name to be applied to the link when it matches the current URL.
This allows you to customize the styling of the link to provide visual feedback to the user.

Dynamic Routing
Dynamic routing is the process of defining routes for different pages of a web application based on the current state of the application or the user's actions.

Dynamic routing can be achieved using parameters in the route path.

Parameters are specified in the route path using a colon followed by a parameter name, such as "/images/:imageId"

import "./App.css";
import { Routes, Route } from "react-router-dom";
import HomePage from './pages/HomePage'
import Images from './pages/Images'
import PageNotFound from './pages/PageNotFound'
import NavBar from "./Components/NavBar";
import ImageDetails from "./pages/ImageDetails";

function App() {
  return (
    <div className="App">
       <NavBar />
      <Routes>
        <Route path="/" element={<HomePage />} /> 
        <Route path="/images" element={<Images />} />     
       ** <Route path="/images/:id" element={<ImageDetails />} />**     
        <Route path="*" element={<PageNotFound />} />

      </Routes>
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

When you have a dynamic route, you want to access the dynamic value in your custom component which is where the useParams hook comes in.

import React from 'react'
import { useParams } from 'react-router-dom'

const ImageDetails = () => {
  const { id } = useParams();
    return (
      <div>
         <p>Image { id }</p>
         {/* Render dynamic content based on the value of `id` */}
      </div>
  )
}
export default ImageDetails
Enter fullscreen mode Exit fullscreen mode

The useParams() hook is provided by the React Router library to extract the value of the id parameter from the current URL.

When a URL matches the path specified in the Route component (e.g., /images/123), the useParams() hook will return an object containing the key-value pair of id: "123", where "123" is the value of the id parameter in the URL.

The code then uses object destructuring to extract the id value from the object returned by useParams(). This creates a new variable named id that holds the value of the id parameter.

So, in the ImageDetails component, the id variable can be used to access the value of the id parameter from the URL and use it to render dynamic content.

Conclusion
Overall, React Router is a powerful tool for managing client-side routing in React applications. It can help make an application more modular, flexible, and easier to navigate, improving the user experience and simplifying development.

Top comments (0)