React Router Introduction
In traditional multi-page websites, clicking a link requests a new HTML page from the server, causing a full page reload. In React, we build single-page applications (SPAs) where all content loads once, and subsequent navigation happens without refreshing the page. **React Router** is the library that makes this possible.
What is React Router?
React Router is a standard library for routing in React. It enables navigation between different components in a React app, keeping the UI in sync with the URL. It allows you to define routes, handle dynamic URLs, and create a seamless user experience.
Think of React Router as the traffic controller of your app. It decides which component to show based on the current URL, without asking the server for a new page.
Why Do We Need Routing?
- Deep linking: Users can bookmark or share specific URLs.
- Back/forward buttons: Browser navigation works as expected.
- Organized code: Different URLs can load different components.
Installation
npm install react-router-domBasic Setup
import { BrowserRouter, Routes, Route } from 'react-router-dom';import Home from './pages/Home';import About from './pages/About';import Contact from './pages/Contact';
function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> </Routes> </BrowserRouter> );}Key Components
| Component | Purpose |
|---|---|
| `BrowserRouter` | Wraps your app and enables routing using the HTML5 history API. |
| `Routes` | Container for all your `Route` components. It decides which route to render. |
| `Route` | Defines a mapping between a URL path and a React component. |
| `Link` | A replacement for `` tags that navigates without page reload. |
Two Minute Drill
- React Router enables navigation in single-page React apps without page refresh.
- `BrowserRouter` wraps the app, `Routes` and `Route` define the URL-component mappings.
- Install via `npm install react-router-dom`.
- Routing provides deep linking, back/forward navigation, and code organization.
Need more clarification?
Drop us an email at career@quipoinfotech.com
