What is React Router?
React router is a library built on top of React used for routing. Sounds pretty obvious, but let’s get into what that really means. React router allows the user to navigate different views of your React application while also allowing you to change the URL and keep the UI in sync with those changes. If you want your React app to have a homepage, an about page, a contact page, profile page, anything like that React router is very helpful.
It’s really easy to install and get started.
npm install react-router-dom
React Router Components
React router has four main components that you’ll need to understand to be able to use them effectively.
BrowserRouter: This is the parent component, meaning that all other components are stored within it. You can do some cool things with BrowserRouter like forcing the browser to refresh and changing the basename of your URL like in the example below.
<BrowserRouter basename="/calendar">
<Link to="/today"/> // renders <a href="/calendar/today">
<Link to="/tomorrow"/> // renders <a href="/calendar/tomorrow">
...
</BrowserRouter>
Route: A Route is a component that renders when its path matches the URL. In the example below if the URL is “/” then the Home component will be rendered but if the app location is “/news” the News component will be rendered.
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";
ReactDOM.render(
<Router>
<div>
<Route exact path="/">
<Home />
</Route>
<Route path="/news">
<News />
</Route>
</div>
</Router>,
node
);
To get a little more technical, no matter what the location of the app is all the components still render, they just render null. All you really need to know is when the route’s path matches the URL, the child component will display on the UI.
Link: A link component creates links to different routes within your React app. Below is a simple example of how a link component works.
<Link to="/about">About</Link>
You can also use a link component with strings, objects, and functions. There’s also the NavLink component which is very similar to a link component but it comes with added styling like changing the color of a NavLink that’s active.
Switch: a switch component renders the first route that matches the location as opposed to rendering every route that matches. The children of switch components should always be either a Route or a Redirect.
React Router is a really powerful tool and I’m glad I went over it to get more clarity. I’ve used it before but now I can envision apps using React Router and have a better understanding of how it works and which ways it can be best put to use. Hopefully this helped you, thank you for reading, and keep coding!