React JS: Routes Basics

Emily Nguyen
2 min readMay 6, 2021

What are routes for?

React routes is a new concept to me, as I learned about them no longer than a few hours ago. Routes are necessary for directing our user to different locations in our application. This happens when a React Route is created properly. It functions by conditionally rendering certain components in the application to display depending on the route in the URL.

Examples of our routes in our URL is www.example.com/about. This is a made up URL so I don’t recommend clicking it, but in this URL the route defined is ‘/about’. This URL will take us to the about page. Here is a short guide to how React Route basics work.

npm install

First thing’s up when building a web app, we need to create our react-app using the ‘npx create-react-app app-name’. Open up the file, cd into the application and in our terminal, we want to install react-router-dom by running the code below.

Importing

Remember to import React, BrowserRouter, Switch, Route and/or Link. One clarification to make is that React is imported from ‘react’ whereas the others listed above come from the ‘react-router-dom’ package we installed in the previous step.

Switch

The Switch component is used to ensure only one component is rendered at a time. This component matches the first route that mirrors its designated path.

Here in the below examples, <Switch> searches through its children and renders the first component whose path matches the current URL. Check out some examples.

Links

Up next, Links allow our user to navigate directly to the specified route. A clickable Link is created on the webpage which will navigate the user to the specified endpoint. There’s many ways to use Link components, but here’s a basic way to use Links. The code below creates a link named “About” which directs the user to the about page when they click on it.

--

--