React Router
React Router
React Router is a library for handling routing in React applications.
It enables navigation and URL manipulation, allowing you to create single-page applications with multiple views.
Here's a basic guide on how to use React Router:
Installation:
You can install React Router using npm or yarn:
npm install react-router-dom
Basic Usage:
Router Setup:
Wrap your application with a 'BrowserRouter' or 'HashRouter' at the root level. The choice between them depends on your hosting environment.
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import NotFound from './components/NotFound';
const App = () => {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route component={NotFound} />
</Switch>
</Router>
);
};
export default App;
Route Components:
Use the 'Route' component to define a route. The path prop specifies the URL 'path', and the 'component' prop specifies the component to render when the path matches.
Navigation:
You can use the Link component to create navigation links:
import { Link } from 'react-router-dom';
const Navigation = () => {
return (
<nav>
<ul>
<li> <Link to="/">Home </Link> </li>
<li> <Link to="/about">About </Link> </li>
</ul>
</nav>
);
};
Route Parameters:
You can use the :param syntax in the path prop to capture URL parameters:
<Route path="/user/:id" component={UserProfile} />
In the component, access the parameter using props.match.params.id.
Nested Routes:
You can nest routes by placing 'Route' components inside the components rendered by other 'Route' components.
const App = () => {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/user/:id" component={UserProfile} />
<Route component={NotFound} />
</Switch>
</Router>
);
};