React Router
What is React Router?
React Router is a popular library for managing and handling routing in a React application. It allows you to create routes that map to specific components in your application, and provides methods for navigating between those routes in a way that maintains the consistency of your UI. This makes it easier to create single-page applications that are easy to navigate and use.
How to use React Router:
Get Isaac Jaquez’s stories in your inbox
Join Medium for free to get updates from this writer.
First, make sure you have installed the react-router-dom package, which provides the components for routing in a React app. Then, import the BrowserRouter component from the react-router-dom package at the top of your component file:
import { BrowserRouter } from 'react-router-dom';Next, wrap your root component with the BrowserRouter component. This will provide the routing functionality to your React app.
<BrowserRouter>
<App />
</BrowserRouter>Now, you can use the Route component to specify which components should be rendered when the app's URL matches a certain path. For example, the following code will render the Home component when the app's URL is /, and the About component when the URL is /about.
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />Finally, you can use the Link component to create links that navigate to different routes in your app. This is similar to using anchor tags in HTML, but it allows the router to handle the navigation instead of the browser.
<Link to="/">Home</Link>
<Link to="/about">About</Link>Let’s put it all together. Here is an example of how you can use React Router by importing the BrowserRouter, Link, and Route components from the react-router-dom package.
import { BrowserRouter, Link, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<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>
</BrowserRouter>
);
}In the code above, the BrowserRouter component is used to wrap the entire app. This enables the routing functionality in the app.
Inside the BrowserRouter, we have a navbar with two links that use the Link component from React Router. These links will navigate to the specified paths when clicked.
Finally, we have two Route components that render the Home and About components when the app is at the specified path. The exact prop is used on the Home route to ensure that it only matches the exact path, rather than any path that starts with /.
This is just a basic example of how to use React Router. There are many other features and options available, so be sure to check out the React Router documentation for more information.
Thank you for reading!









