React Router Basics

Chandler Hanson
3 min readNov 23, 2020
Photo by Denys Nevozhai on Unsplash

React is a library that specializes in creating single-page applications (SPAs) that are rendered on the client side. This means the client side is in charge of handling the routing, fetching and displaying of the data in the browser rather than the server. SPAs tend to have multiple pages (routes) on them. Client-side routing gets all the needed data to render all the pages on the first page load. Navigating these pages do not require the entire page to be reloaded. An SPA can achieve this by using the React routing library React Router.

Using React Router

To install React Router, run:

npm install react-router-dom

Note that the actual component is called BrowserRouter but it is commonly renamed as Router.

<Router> tag is the base of our application’s routing. The <Route> component kind of acts like a function. The component is rendered when the URL matches the specific path. There is one problem, <Router> can only one child element. To bypass this dilemma, we wrap all the <Route> components in a <div> tag. This is what it looks like for using multiple routes.

<Navbar> and <Navlink>

To look at all the components, you can find this project’s GitHub repository here. Something to note is the <Navbar> component. The <Navbar> is not a route, but its own separate component. Since it is not a route, it will always be on the webpage no matter which route you are on.

<Navbar> is a bar at the top of the screen to easily switch between routes. Users would not know how to find these routes or what they are without some sort of functionality like this. <Navbar> uses <NavLink> tags to trigger our routing.

<Navlink> is used to define and design a declarative navigation around an application. This will cause the page to route to the specified route when it is clicked on. <Navlink> tag can also add styling attributes to the rendered element.

This is a good website to look at other examples and guides about React Router.

https://reactrouter.com/web/example/basic

--

--

Chandler Hanson

Flatiron School software engineering alum. Experienced in JavaScript, React.js, Ruby, and Ruby on Rails. https://www.linkedin.com/in/chandler-hanson/