React Router
React Router is a popular library for routing in React applications. It provides a declarative way to handle navigation and define routes in your application, allowing you to render different components based on the URL.
Here’s an overview of React Router:
- Installation:
You can install React Router using npm or yarn:
npm install react-router-dom
or
yarn add react-router-dom
- Basic Usage:
React Router provides several components to define routes in your application. The most commonly used components areBrowserRouter
,Route
, andLink
.
BrowserRouter
: Wraps your application and provides routing functionality.Route
: Defines a route and specifies which component to render when the URL matches the route path.Link
: Provides declarative navigation by rendering an anchor tag (<a>
) that changes the URL when clicked.
- Example:
Here’s a basic example of how to use React Router in your application:
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
</Router>
);
}
export default App;
- Nested Routes:
React Router supports nested routes, allowing you to define routes within other routes. This is useful for creating complex application layouts with multiple levels of navigation. - Route Parameters:
You can use route parameters to match dynamic segments of the URL and pass them as props to the rendered components. - Programmatic Navigation:
React Router provides ahistory
object that allows you to perform navigation programmatically, such as pushing, replacing, or going back and forth in the browser history.
React Router simplifies navigation and routing in React applications, making it easy to create single-page applications with multiple views and layouts. It’s a powerful tool for building complex user interfaces with client-side routing functionality.