React Router

23-Jan-2024

React Router

React Router is a popular library for handling navigation and routing in React applications. It enables you to create single-page applications (SPAs) with dynamic and client-side routing.

In React applications, navigation refers to how users move between different views or pages. React Router provides a powerful and declarative way to handle routing, allowing you to update the UI based on the URL.

Key Concepts:

Installation:

npm install react-router-dom
Basic Usage:


import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; const Home = () => <h2>Home</h2>; const About = () => <h2>About</h2>; const App = () => ( <Router> <div> <nav> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> </ul> </nav> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </div> </Router> ); export default App;

  • BrowserRouter provides the foundation for navigation.
  • Link components create links for navigation.
  • Route components define the association between a URL path and a component to render.

Route Parameters:

import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; const UserProfile = ({ match }) => ( <div> <h2>User Profile</h2> <p>User ID: {match.params.userId}</p> </div> ); const App = () => ( <Router> <div> <nav> <ul> <li><Link to="/user/123">User Profile</Link></li> </ul> </nav> <Route path="/user/:userId" component={UserProfile} /> </div> </Router> ); export default App;
Nested Routing:
import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; const Home = () => <h2>Home</h2>; const UserProfile = () => <h2>User Profile</h2>; const App = () => ( <Router> <div> <nav> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/user">User Profile</Link></li> </ul> </nav> <Route path="/" exact component={Home} /> <Route path="/user" component={UserProfile} /> </div> </Router> ); export default App;
Components can be nested within Route components for hierarchical navigation.

Use Cases:
  • SPA Navigation: Creating single-page applications with seamless navigation.
  • Conditional Rendering: Showing or hiding components based on the current route.
  • Authentication: Protecting certain routes based on user authentication.
React Router simplifies navigation in React applications, providing a clean and declarative way to handle different views and URLs.

Comments