DEV Community

Cover image for How To Use React Router Dom In React JS
Udemezue John
Udemezue John

Posted on

How To Use React Router Dom In React JS

Introduction

When I first started building projects with React, I quickly learned that managing navigation between different parts of an app can be tricky.

React Router Dom comes in as a lifesaver for creating dynamic and responsive single-page applications.

It gives you the tools to switch between pages or components without the need for a full-page reload.

This creates a seamless experience for users and makes your code easier to maintain.

Many developers, including myself, appreciate React Router Dom because it allows us to define routes directly in our React components.

The package has grown in popularity, with millions of downloads on npm and positive feedback from the community.

If you want to build web applications that are easy to navigate, this guide will help you understand the key concepts and practical steps needed to get started.

Why React Router Dom Matters

React Router Dom is the go-to solution for client-side routing in React JS.

It handles the mapping of URLs to the components that should be rendered, making it possible to build complex interfaces with multiple views.

This means that instead of reloading the entire page, only the components that need to change are updated, which can significantly speed up your app.

Some benefits I’ve experienced using React Router Dom include:

  • Smoother User Experience: Navigation happens within the app without any full-page refreshes.
  • Cleaner Code Structure: Routing logic stays with your component code, making it easier to manage and debug.
  • Better Performance: Only necessary parts of the page update, which can reduce load times.
  • Easy to Learn: With clear documentation and a supportive community, React Router Dom is accessible even if you are new to routing.

For more details, you can always refer to the official React Router documentation.

Getting Started with Installation

Before you can start using React Router Dom, you need to install it. It’s simple and can be done with npm or yarn. Here’s how I installed it:

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

Or, if you prefer yarn:

yarn add react-router-dom
Enter fullscreen mode Exit fullscreen mode

Once installed, you can import the components you need into your React project. The basic setup involves using components like BrowserRouter, Routes, Route, and Link.

Basic Concepts of React Router Dom

Understanding a few core ideas can make it much easier to use React Router Dom. Here are the main concepts:

  • BrowserRouter: This component wraps your entire application. It listens for changes to the URL and ensures that the correct components are displayed.
  • Routes and Route: The Routes component is a container for all the Route components. Each Route specifies a path and the component to render when that path is matched.
  • Link: Instead of traditional anchor tags, the Link component lets you create navigation links within your app. It helps in navigating without refreshing the page.

Let’s look at a small example:

import React from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

function Home() {
  return <h2>Home Page</h2>;
}

function About() {
  return <h2>About Page</h2>;
}

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link> | <Link to="/about">About</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, I wrap the entire app in <BrowserRouter>, which monitors URL changes. I define a couple of routes inside <Routes>, and each route points to a different component.

The <Link> components create navigable links that do not reload the page. This code is straightforward and shows the basics of how to set up routing.

Exploring Further: Nested Routes and Dynamic Routing

One of the powerful features of React Router Dom is its ability to handle nested routes. This means you can have routes inside other routes.

This is useful when you want to create a layout that includes a common header or sidebar while changing the main content area based on the URL.

For instance, imagine you have a user dashboard with sections like profile, settings, and messages.

Instead of creating separate pages for each, you can nest these routes under a main dashboard route:

function Dashboard() {
  return (
    <div>
      <h2>User Dashboard</h2>
      <nav>
        <Link to="profile">Profile</Link> | <Link to="settings">Settings</Link>
      </nav>
      <Routes>
        <Route path="profile" element={<Profile />} />
        <Route path="settings" element={<Settings />} />
      </Routes>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Dynamic routing is another useful feature. It allows you to define routes that include variables. For example, if you have a blog and want to render a post based on an ID from the URL, you can do this:

function Post() {
  const { id } = useParams(); // useParams hook fetches the dynamic parameter
  return <div>Now showing post {id}</div>;
}
Enter fullscreen mode Exit fullscreen mode

In your routes, you might set it up like this:

<Route path="/post/:id" element={<Post />} />
Enter fullscreen mode Exit fullscreen mode

This code lets the app render the correct post based on the id in the URL.

Common Issues and Tips

While working with React Router Dom, I’ve encountered a few common pitfalls. Here are some tips that might help:

  • Component Hierarchy: Make sure that the BrowserRouter wraps around all components that need access to routing. If a component is outside of it, you might see errors.
  • Exact Paths: In earlier versions of React Router Dom, using the exact keyword was necessary to avoid matching routes too broadly. With version 6 and above, this is handled automatically.
  • Link vs. Anchor Tags: Always use <Link> for navigation within your app. Using traditional anchor tags (<a>) forces a page reload, which negates the benefits of a single-page application.
  • 404 Pages: It’s a good idea to include a fallback route that displays a 404 message when no other routes match. For example:
  <Route path="*" element={<NotFound />} />
Enter fullscreen mode Exit fullscreen mode
  • Using Hooks: The library provides hooks like useParams, useNavigate, and useLocation that can make your life easier when managing dynamic routes or programmatic navigation. Explore them to see how they can improve your routing logic.

FAQ

Q: What is React Router Dom?

A: React Router Dom is a library that manages the routing in a React JS application. It allows you to handle navigation and URL management within a single-page application. For more details, check out the React Router Dom documentation.

Q: How do I install React Router Dom?

A: Installation is simple. You can install it via npm with the command npm install react-router-dom or with yarn using yarn add react-router-dom.

Q: Can I use React Router Dom with older versions of React?

A: Yes, React Router Dom works with many versions of React. However, make sure you are using a version of React Router that is compatible with your React version. The official docs provide guidance on compatibility.

Q: How do I handle nested routes?

A: You can nest <Route> components inside a parent route. This setup helps you manage different views within a shared layout. The earlier dashboard example is a common pattern.

Q: What if my app has routes that don't match any defined path?

A: It’s a good practice to add a catch-all route that renders a “Not Found” component. This ensures that your users see a friendly message if they enter an incorrect URL.

Additional Resources

  • React Router Official Docs: The best place to understand all the features is the official documentation.
  • NPM Package Page: View download statistics and package details on npm.
  • Tutorials and Blogs: Sites like freeCodeCamp and Dev.to often have useful tutorials on how to implement React Router Dom in different scenarios.
  • Community Forums: For tips and troubleshooting, forums like Stack Overflow are a good resource.

Conclusion

I hope this guide has helped clear up the basics and some advanced features of React Router Dom in React JS.

Understanding routing is a key step in building modern web applications, and with tools like React Router Dom, the process becomes much more manageable.

I shared my tips and code examples to show how you can start with simple routes and move on to more dynamic and nested routing.

What are your thoughts on how to use React Router Dom in React JS?

Top comments (0)

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!