DEV Community

Vishal Gaurav
Vishal Gaurav

Posted on

Getting started with React Router

  • In this blog we are going to see the basics of React Router and get started with the first steps.

The Basics

  1. React Router is a client side library for React and React Native.

  2. It makes navigating to different pages possible without needing a refresh.

  3. Both declarative routing and imperative routing are supported.

The First Use

We will be implementing the router in a new project and learn the concepts step by step.

  • Install the router using the command $ npm install react-router-dom@6
  • Create two pages which will point to the two routes we are going to create.
const FeedPage = () => {
  return <div>This page shows feeds.</div>;
};
export { FeedPage };
Enter fullscreen mode Exit fullscreen mode
const UserPage = () => {
  return <div>This page shows the details of a user.</div>;
};
export { UserPage };
Enter fullscreen mode Exit fullscreen mode
  • Import the BrowserRouter, Routes and Route from "react-router-dom". Wrap the whole project with BrowserRouter. This is necessary for react-router to work. Nest the Routes inside BrowserRouter. Now add a Route element for each route you want to specify.
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { FeedPage, UserPage } from "./pages";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="feed" element={<FeedPage />} />
        <Route path="user" element={<UserPage />} />
      </Routes>
    </BrowserRouter>
  </StrictMode>
);

Enter fullscreen mode Exit fullscreen mode

Here, /feed will point to FeedPage and /user will point to UserPage respectively.

  • We can now see that adding feed or user to the root / in the address bar takes us to the corresponding page. routing to feed

routing to user

  • Voila! We just implemented the bare minimum react-router.

Navigating using Links

Navigating to routes by changing the address manually is not very convenient, We will use now Link component to navigate to the desired page.

  • Create a Homepage where we will be adding two link components to navigate.
<Route path="" element={<HomePage />} />
Enter fullscreen mode Exit fullscreen mode
  • Import and add two Link components into the HomePage
import { Link } from "react-router-dom";

const HomePage = () => {
  return (
    <div>
      <div>
        <Link to="feed">Feed</Link>
      </div>
      <div>
        <Link to="user">User</Link>
      </div>
    </div>
  );
};
export { HomePage };
Enter fullscreen mode Exit fullscreen mode

Links are similar to anchor tags but they do not lead to page refresh. Now clicking on the links take us to the corresponding page.

The URL Params

Navigating to a route is good but what if we need to list a particular user using some identifier such as userId?

  • Edit the user route so that it takes in a userId as a parameter.
<Route path="user/:userId" element={<UserPage />} />
Enter fullscreen mode Exit fullscreen mode
  • Edit the Link in HomePage to
<Link to={`/user/${123}`}>User</Link>
Enter fullscreen mode Exit fullscreen mode

Here 123 is the parameter value passed to the user route.

  • We can read the passed param from the UserPage using useParams() hook as follows. Note that the param name which we used in Route component will be used to access the param from the UserPage.

We read the passed param as follows:

import { useParams } from "react-router-dom";

const UserPage = () => {
  let params = useParams();
  return <div>This page shows the details of user {params.userId}.</div>;
};
export { UserPage };
Enter fullscreen mode Exit fullscreen mode
  • Now we can see that on clicking the Link on homepage we are successfully routed to the given userId. navigating to the userId

The No Match Route

What if a user accidentally is routed to route which is not defined? For this purpose we can add a Route with '*' as path inside our Routes. This route will be matched when none of then path matches.

  • Add a no match route as follows.
<Route path="*" element={<div>Page not found!</div>}/>
Enter fullscreen mode Exit fullscreen mode
  • Now when we go a route which is not defined we will get a proper message that the page does not exists! no=match

Navigating Programatically

Till now we have seen only one way of navigating to routes which is through <Link>. What if we need to navigate to a route after some action is performed such as button click or a page reload? We have useNavigate() hook which allows us to do that.

  • Let's add a button to Homepage. On click of this button we will navigate to FeedPage.
import { useNavigate } from "react-router-dom";

const HomePage = () => {
  let navigate = useNavigate();
  const buttonClickHandler = () => {
    navigate("feed");
  };
  return (
    <div>
      <button onClick={buttonClickHandler}>Feed Page</button>
Enter fullscreen mode Exit fullscreen mode
  • We can now see that on click of button we are successfully navigated to the Feed page.

Demo

End

So this was all about the intro React Router. I hope it was beginner friendly to new users off React-Router. Please drop in your feedback or comments.

Have a good day!

Top comments (0)