Lecture: Routing in React Applications with React Router
Introduction
- Current application has only one page.
- Most websites have multiple pages.
- Need to introduce multiple routes in React applications using
react-router
.
Traditional Multi-Page Website
- Start by typing a URL -> request sent to server -> server responds with full HTML page.
- Clicking on links sends new requests to the server for new HTML pages.
- This cycle repeats for every new page request.
React Applications
- Initial request -> server sends back HTML + compiled React JS files.
- React and React Router handle routing within the browser afterward.
- React dynamically injects content into initially empty HTML.
- Clicking links: React Router intercepts requests and injects the required content without going back to the server.
React Router Overview
- Assign a top-level component for each route.
- Dynamically inject components based on route changes.
- Reduced server requests -> faster and smoother user experience.
Setting Up React Router
Installation
- Use
npm
to install the React Router package.
npm install react-router-dom@5
- Verify installation in
package.json
(e.g., "react-router-dom": "5.2"
).
Usage in Code
Root Component (App.js)
- Import Statements
import {
BrowserRouter as Router,
Route,
Switch
} from 'react-router-dom';
- Wrap Application with Router
<Router>
{/* Your App Components */}
</Router>
- Set Up Routes
<Switch>
<Route path="/" component={Home} />
</Switch>
- Adding Routes for Other Pages (e.g., About, Contact)
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
Switch
component ensures only one route is rendered at a time.
- Navbar rendered outside of
Switch
to show on all routes.
Next Steps
- Preview changes.
- Add more routes and understand the
Switch
component.