D Dev Notebook

React Router DOM

React Router DOM

dev notebook

What is react-router-dom?

react-router-dom is a standard routing library used in React applications to handle navigation between different pages or views in a Single Page Application (SPA).

In a SPA, there's only one page, and react-router-dom lets you simulate multiple pages by showing/hiding components based on the current URL.

Installation

npm install react-router-dom

Routes and Route

  • Define what component to show for a given path. (App.js)
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
// Import your pages/components
import Home from './pages/Home';
import About from './pages/About';
import NotFound from './pages/NotFound';
import Navbar from './components/Navbar';


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

export default App;

Used instead of <a> tags to change the URL without reloading the page. (Navbar.jsx)

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

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

export default Navbar;

On this page