DEV Community

Cover image for Routing with React Router
Paul Vitalis
Paul Vitalis

Posted on • Updated on

Routing with React Router

Navigating through pages in a React application is made possible using a library called React Router Dom.

We will walk through Routing with an example.

First we will use vite to quickly spin up a React project.

npm create vite@latest

Enter your project name and select all options you would prefer when prompted.

Here is my preferred configuration.

Configuration

Install all dependencies using npm install

To install react-router-dom, run the following command

npm i react-router-dom

Run the app using npm run dev

Create a components folder under the src directory and then create two components: Home and About inside the components folder.

ROUTING

For routing, create a folder called router under src and within it, create index.tsx.

Our folder structure should now look like this:

Folder Structure

Now inside our router file, we will create routes for our Home and About pages as follows.

import { createBrowserRouter } from "react-router-dom";
import Home from "../components/Home";
import About from "../components/About";


const router = createBrowserRouter([
  {
    path: "/",
    element: <Home/>,
  },
  {
    path: "/about",
    element: <About />,
  },
]);

export default router;

Enter fullscreen mode Exit fullscreen mode

Note that we imported createBrowserRouter from react-router-dom. This is the recommended router for all React Router web projects. It uses the DOM History API to update the URL and manage the history stack.

We then go to our App.tsx file and replace everything within it as follows.

App.tsx

import "./App.css";
import { Outlet } from "react-router-dom";

function App() {
  return (
    <>
      <Outlet />
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

You'll notice we imported Outlet from react-router-dom and added it in our return statement. An Outlet should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route. In this case, our parent route element is the App.tsx file and the child routes are Home.tsx and About.tsx

Lastly, we will update our main.tsx file with RouteProvider from react-router-dom

We import our router first and pass it into RouterProvider. All data router objects are passed to this component to render your app and enable the rest of the data APIs.

main.tsx

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import router from "./router/index.tsx";
import { RouterProvider } from "react-router-dom";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

Enter fullscreen mode Exit fullscreen mode

Now if we go to the browser you can navigate routes between our two pages!

Home Page

Home Page

About Page

About Page

That's all you need! Or is it?

Suppose you tried accessing a route like /home, what do you think will happen? Let's see.

Error

Yikes! We had not specified a route for /home. We only put two routes: / and /about. To fix this, we can add a route to handle non-existent routes.

Firstly, create a component that will render whenever a user accesses a non existent route.

import React from "react";

const Error = () => {
  return <div>This is the error page</div>;
};

export default Error;

Enter fullscreen mode Exit fullscreen mode

Next, we go to our router file, import the Error component we just created, and add a path to handle non-existent routes as follows:

 {
    path: "*",
    element: <Error />,
  },
Enter fullscreen mode Exit fullscreen mode

And this is our result if we go to a non-existent route:

Non existent

This tutorial is just a tip of the iceberg when it comes to React Router. I would encourage you to explore more and see what React router has to offer you. The full documentation of react-router can be found at: https://reactrouter.com/en/main

Follow me on:
LinkedIn: Paul Otieno
Twitter: me_huchoma
Instagram: paul_dreamer_

Happy Coding! 🥂

Top comments (1)

Collapse
 
sharmi2020 profile image
Sharmila kannan

Nice article one about routing