Routing allows you to create a single-page web application with navigation, without the need for a full-page refresh.
React Router is a library for handling routing and enables navigation and rendering of different components based on the URL.
- Install React-Router
- Create Navigation
- Create Routes
npm install react-router-dom
import React from 'react';
import { Routes, Route, Link } from 'react-router-dom';
// Elements or imported components
const Home = () => <h2>Home</h2>;
const About = () => <h2>About</h2>;
const Contact = () => <h2>Contact</h2>;
const AppRoute = () => (
<div>
{/* Navigation links */}
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
import AppRoute from './Others/AppRoute';
import { BrowserRouter as Router } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Router>
<AppRoute />
</Router>
);
{/* Routes */}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
);
export default AppRoute;
- The component is used as the root container for declaring your
collection of routes
. - The component is used to define a route and specify the component that should render when the
route matches
.- For example, in this code if user enter "websitename.com/about [invalid URL removed]" in url, then matching "About" component will be rendered.
import React from 'react';
import { Routes, Route, Link } from 'react-router-dom';
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
Route parameters in React Router are a way to pass dynamic values(data) to the component as part of the URL path
.
{/* userId is the route parameter */}
<Route path="/users/:userId" component={UserProfile}/>
- Switch component ensures that only the
first matching <Route> is rendered
and rest are ignored.- For example, Switch is commonly used to handle 404 or "not fount" routes.
import {Switch, Route} from 'react-router-dom';
<Switch>
<Route path="/users" component={UserList}/>
<Route path="/users/:id" component={UserProfile}/>
</Switch>
exact prop is used with the component to match exactly
to the provided path.
{/*Without exact (default behavior)*/}
{/*Match /about, /about/team, /about/contact, etc.*/}
<Route path="/about" component={About} />
{/*With exact*/}
{/*Only match /about*/}
<Route path="/about" exact component={About} />