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:
Basic Usage:npm install react-router-dom
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;
Route Parameters:
Nested Routing: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;
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;