What Is React Router? Complete Basics Guide With Example

React Router is a library for routing in React apps. It allows you to navigate between different components without reloading the page, creating a single-page application (SPA) experience.


Installing React Router

npm install react-router-dom

Basic Usage

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

function Home() {
  return <h2>Home Page</h2>;
}

function About() {
  return <h2>About Page</h2>;
}

function App() {
  return (
    <Router>
      <nav>
        <Link to="/">Home</Link> | <Link to="/about">About</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}

Key Points

  • BrowserRouter → wraps the app for routing
  • Routes → contains all route definitions
  • Route → defines a single route
  • Link → navigates between routes without page reload

Dynamic Routes Example

<Route path="/user/:id" element={<User />} />

function User() {
  const { id } = useParams();
  return <h2>User ID: {id}</h2>;
}

Conclusion

React Router is essential for navigation in SPAs, allowing dynamic routes, smooth transitions, and organized app structure.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *