Alexander Karan
Alexander Karan's Blog

Alexander Karan's Blog

URLs, Routes and React Router

Photo by Remotar Jobs on Unsplash

URLs, Routes and React Router

Understanding how to use URLs and how to create routes in React

Alexander Karan's photo
Alexander Karan
·Apr 10, 2022·

8 min read

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • React Router and Create React App
  • Example app
  • Conclusion

Disclaimer: I created this blog and content to help my 2022 SheCodes Australia Plus cohort understand the basics of URLs and React Router

You click a link, a button or a navigation element, something loads and the page changes. How do we set this up in React? What's going on under the hood to make the page change? When using React with Create React App, the easiest way to set up routes is to use React Router. Before we take a closer look at React Router, let's look at a URL and go over its makeup and how it works.

Here is an example URL:

A314749D-9713-491B-852D-01ED43339646.jpeg

www.jeans.com is the base URL referred to as the domain or origin. It is the address of the website. It tells web traffic which server to point to, the one with the code/content for www.jeans.com when someone types it in their browser.

/skinny personally, my favourite type of jeans is a path parameter or param. Different path parameters typically control the load of pages or drastically change the page's contents. /skinny is a good example here. I am on a website that sells jeans. I have clicked the type that I want, and the website has directed me to a new page in my browser that shows all the different styles and colours of skinny jeans.

color=blue is called a query or sometimes called a query param. A query slightly alters what you see on the page. In this jeans example, we have a filter for brand, colour and size on the page. Setting the colour to blue adds the query on the end of the URL and filters the jeans I see on the page.


React Router and Create React App

Usually, when you click a link to a new page in an app, for example, going from home to contact, your browser makes another request to the server. If your browser could talk, it says I have the HTML, files or content for the home page to the server. Can you now send me the HTML, files or content for the contact page?

However, when we use Create React App, we send JavaScript for the whole app to the browser and create a single-page app. That means under the hood were loading one app and one page, but we use tools like React Router to make the URL and app behave like the example I gave before. Another way of thinking about it is the URL is state just like the useState hook inside react. Your UI should interact and change based on what is in the URL.


Example app

The best way to understand new concepts is to build something. Let's spin up a small app using my jeans concept. First, set up a new project with Create React App using the following command in the terminal npx create-react-app routes-and-jeans.

Wait for it to set up the project, cd into the folder using cd routes-and-jeans. Next, let's install React Router to use it in our project npm install react-router-dom@6. Once installed, let's run the app to ensure everything is working by typing in npm run start.

Set up

To create routes (pages) in our app, we need to wrap the app in the component calledBrowserRouter. Head to the index.js file inside the src folder. Add the following line at the top of the page after all the other imports.

import { BrowserRouter } from "react-router-dom";

Then wrap your app the component in BrowserRouter. Your index.js file should look like this:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Wrapping our app with the BrowserRouter component means we can create routes anywhere in the app. We can also access the URL, browsing history of our site, path params and queries.

Next, let's create three new pages to use in our app. I will make a folder called Pages inside the src folder. Inside my new folder called Pages, I will create three new folders named HomePage, JeansPage, and ContactPage. Inside each folder, create an index.js file and add the following code:

import React from "react";

function HomePage() {
  return <h1>I am the home page</h1>;
}

export default HomePage;

Make sure you update the name in the code to match the folder you put it in. For example, when adding it to the ContactPage index file, change the component name to ContactPage and update the heading to say contact page.

Creating our routes

Now that we have created our base page components, it is time to head to our app.js file and create our routes. You can delete all the code in the file and replace it with the following code. I left some comments to explain what I am doing, but you can delete those.

import { Routes, Route } from "react-router-dom";

// Pages
import HomePage from "./Pages/HomePage";
import JeansPage from "./Pages/JeansPage";
import ContactPage from "./Pages/ContactPage";

// CSS
import "./App.css";

function App() {
  return (
    <div className="App">
      <h1>For all your jeans needs!</h1>

      {/* When creating Route components, they have to be wrapped by Routes. */}
      <Routes>
        {/* Here we are creating our home page route. We set the path to "/" as it is the starting page in our app, and we pass in the component we want to load to the element prop. */}
        <Route path="/" element={<HomePage />} />

        {/* Setting the path to "contact" will load the contact page component at the URL /contact. No need to add the slash as it is implied by default when working from the base URL */}
        <Route path="contact" element={<ContactPage />} />

        {/* Setting the path ":jeans" means it is a dynamic path param. It is a parameter that is changed based on something happening in the app. Any URL that does not match "/" or "/contact" and has something after the base URL will cause the element in this route to load. Don't worry if you are not 100% sure what this means; you will see it in action later. */}
        <Route path=":jeans" element={<JeansPage />} />
      </Routes>
    </div>
  );
}

export default App;

Finally, to allow us to navigate to our other pages, we need to add some links to our home page. Open the HomePage component and change the code to match my example. Once again, I have added comments to explain a few things.

import React from "react";
import { Link } from "react-router-dom";

function HomePage() {
  return (
    <main>
      <h2>Home Page</h2>
      {/* Here we are creating a simple navigation element on the home page.  */}
      <nav>
        <ul>
          <li>
            {/* You should still use the `<a></a>` HTML tag when linking to something outside the app. However, now, when linking to other pages or content inside the app, we use the React Router `Link` component. */}
            <Link to="/bootcut">Bootcut Jeans</Link>
          </li>
          <li>
            {/* To tell the link where to navigate, we add the URL to the to prop.  */}
            <Link to="/skinny">Skinny Jeans</Link>
          </li>
          <li>
            <Link to="contact">Contact Us</Link>
          </li>
        </ul>
      </nav>
    </main>
  );
}

export default HomePage;

Head to your app in the browser, and you will see the following on the home page at the base URL http://localhost:3000/.

Screen Shot 2022-04-10 at 9.01.17 am.png

Click the contact page link, and the URL should change to http://localhost:3000/contact, and the page should reload and show you the contact page.

Screen Shot 2022-04-10 at 9.01.25 am.png

Click back in the browser, and you should be back on the home page. If this has not happened for you, double-check your added code. I have also included a link to the example app on Github at the end of the blog.

Path params

Head to the JeansPage component and add a new function that allows us to access the path parameter.

import React from "react";
import { useParams } from "react-router-dom";

function JeansPage() {
  /**
   * useParams is a hook (function) that allows us to access the path param. Earlier, when we set the path of the route component that loads the jeans page, we added the path param `: jeans` into the URL.
   * We can access whatever value is put in this URL section using useParams and then access the value using the same key, `jeans`.
   */
  const params = useParams();

  return (
    <div>
      <h2>{params.jeans}</h2>
    </div>
  );
}

export default JeansPage;

We're now injecting the path parameter into the <h2></h2> element. You should see it updated on the page when the path parameter changes. Head back to the home page and click Bootcut Jeans; you should see the following:

Screen Shot 2022-04-10 at 9.14.29 am.png

Your URL should also contain bootcut http://localhost:3000/bootcut. Click back and press the Skinny Jeans link, and now the title on the page should change to skinny, and the URL matches skinny too. Here you can see path params at work.


Conclusion

If you want to check out my example project, you can find all the code here on Github. For further reading on React Router, they have excellent docs and examples; check out their introduction section.

If you have any questions about what I have covered or spot a mistake, you can reach me here or on Twitter.

 
Share this