React Router



This content originally appeared on DEV Community and was authored by Chithra Priya

React Router:
React Router is a library for handling routing and navigation in React JS Applications. It allows you to create dynamic routes.It enables navigation in a single-page application (SPA) without refreshing the entire page.

Why use React Router?

  • Enables navigation between views/pages
  • Keeps UI in sync with the URL
  • Avoids full page reloads (SPA behavior)
  • Offers route parameters, nested routes, redirects, etc.

Installation:

npm install react-router-dom

Example Program:

jsx file:

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

function NavBar() {
  return (
    <nav>
      <Link to="/">Home</Link> | 
      <Link to="/about">About</Link>
    </nav>
  );
}

App.jsx (or) App.js:

// App.jsx or App.js
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';

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

export default App;
  • BrowserRouter – Wraps the app to enable routing
  • Routes – Grouping all Route elements
  • Route – It has two arguments (Path, Element)


This content originally appeared on DEV Community and was authored by Chithra Priya