Beginner's guide to React Router

Beginner's guide to React Router

Introduction

React Router is a powerful routing library for React applications. It allows developers to declaratively define routes, handle navigation, and manage the URL of a React app.

React Router is easy to learn and use, even for developers who are new to React. The library provides a simple API with clear documentation, making it easy to get started with routing in your app.

React Router allows you to define your routes in a declarative manner, using components such as Routes, Link, and Route. This makes it easy to understand and maintain the routing configuration of your app.

Import and Install React router

Install the library using npm or yarn

npm install react-router-dom
//Or
yarn add react-router-dom

We will create some components in our file, which will be the Home and About pages.

Home.js

function Home(){
    return (
    <div>
    <h1>Home</h1>
    </div>
    )
}

export default Home;

About.js

function About(){
    return (
    <div>
    <h1>Home</h1>
    </div>
    )
}

export default About;

Configuring the root component

To use the library, we have to wrap our elements inside the BrowserRouter

Inside the root component import and wrap <BrowserRouter>

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";

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

root.render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>
);

Define your Routes using the Routes Component

Inside your App Component, Define your routes using the Routes Component

App.js

import { Routes, Route,Link} from "react-router-dom";

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/about" element={<About />} />
  <Route path="/contact" element={<Contact />} />
</Routes>

Inside the App.js

<nav>
  <Link to="/">Home</Link>
  <Link to="/about">About</Link>
  <Link to="/contact">Contact</Link>
</nav>

Summary and Further Readings

This is just a basic introduction to React Router, the library is vast and has more features as well, you can check out some of the following resources to dive deep into the library.

https://reactrouter.com/en/main/start/tutorial

https://www.youtube.com/playlist?list=PLC3y8-rFHvwjkxt8TOteFdT_YmzwpBlrG

https://www.npmjs.com/package/react-router-dom

Did you find this article valuable?

Support Divij Sehgal by becoming a sponsor. Any amount is appreciated!