Routers, also known as routing libraries, allow developers to create single-page applications that can easily handle navigation and URL changes without needing to reload the whole page or perform a redirect. This helps improve user experience by allowing them to seamlessly transition between different parts of an application while still keeping all the necessary data intact.
Here is an example of how to use React Router to handle routing in your application
import React from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
export default 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>
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
);
}
In this example, the BrowserRouter component is used as the top-level component for handling routing. The Link component is used to create links that navigate to different routes. The Switch component is used to render the first route that matches the current URL. The Route component is used to define the routes and to map URLs to specific components.
You can also use useParams hook to access the parameters of a route. import { useParams } from "react-router-dom";
function User() {
let { id } = useParams();
return <h3>ID: {id}</h3>;
}
function App() {
return (
<Router>
<div>
<nav>
<Link to="/">Home</Link>
<Link to="/user/42">User 42</Link>
</nav>
<Switch>
<Route path="/user/:id">
<User />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
);
}