React Training
  • React JS Library
  • Roadmap
  • Training OutLine
  • React js basics
    • Understanding React JS
    • React JS a framework?
    • Setting Up React
    • Say Hello to React
    • Everything is a Component
    • Create-react-app
  • React Building Blocks
    • JSX and Babel
    • One Way Data Flow
    • Virtual DOM
    • V of MVC
    • React Terminology
    • React Tooling
  • Day 01
    • Day 01 OutLine
    • All About JSX
    • React Tools/ npm & webpack
    • Introduction of Webpack
    • Hello world using webpack
      • Webpack Setting up with React
    • NPM Scripts | Package JSON
      • Package.json file
    • React JS Principles
      • One Way Data Flow
      • V of MVC
      • Virtual DOM
    • Create React App - Part-1
    • Create React App - Part-2
  • Day 02
    • Quick Recap
      • Quiz
    • State & Props
      • State & Props in Depth
      • State Vs Props | Compare
    • React LifeCycle Methods
      • React LifeCycle Methods for V-0.16 x
    • Constructor | Lifecycle
    • Write Flicker App | First App
  • Day 03
    • Quick Recap
    • Life Cycle Flow
      • Birth and Mounting
      • Initlization and Construction
      • Pre Mounting
      • Render Method
      • componentDidMount
    • Type of React Components
      • Examples- Quick Compare
      • Class and Functional components
      • Functional Components
    • YouTube application
      • Component Design
    • All in One LifeCycle
  • Assignment
    • React App development
  • Day 04
    • Quick Recap on Lifecycle
    • Lifecycle deprecated/New Methods
      • New Lifecycle Methods
    • Lets Build App Netflix | Mock
  • Assignment
    • Github battle App | Assignment
  • Day 05
    • Quick Recap : Hooks
    • ES6 Features | Hands-on
      • ES6 Code Examples
    • Next Stop - React Router | SPA
      • Code examples | Router
      • React Router Building Blocks
      • Application using react-router-dom
  • Day 06
    • Router V4 | Quick Recap
    • ES2015 | 16 Quick Recap
    • LifeCycle Methods -Part-1
    • LifeCycle Methods -Part-2
  • Day 07
    • Quick Recap | New Lifecycle
    • Quick Recap | React Routing
    • Context API | React JS
      • component with context APIs
      • Context API | examples
    • App using Hooks/Context APIs
  • Assignment
    • Assignments
  • State Management Day-08
    • Quick Recap
    • Managing React State
      • What is Redux
      • Understanding Redux
      • Hello World "Redux"
  • React Redux Day - 09
    • Redux State Manager
    • Redux Redux Development
    • Simple Application | Redux
  • Redux Live Application Day -10
    • Redux with existing Application
      • Redux with React App
      • Lets Build More Apps
      • Should I use Redux from Dan
    • Quick Look at JS in React
    • Learn By Reading
  • miscellaneous Items - Day 11
    • Hooks useReducer
    • Hooks useContext
    • Hooks useRef
    • Hooks useEffect
    • Hooks useState
    • Lazy Loading and code splitting
    • Styling React Component
  • React Next Step - Day 12
    • Topics
    • Jest and Enjyme Testing
    • Examples: Testing
  • React Native
    • What is React Native
    • Setting up Environment
      • Linux Systems
    • React Native Hello World App
    • React Native Architecture
    • React Native Vs Native
    • Expo Cli or React Native CLI
  • React Native core Fundamental
    • React Native "Hello World"
    • Course OutLine
    • Getting started with Expo App
    • Layout with Flexbox
    • Working with Styles and Events
    • Manging Component State and Props
    • Build Simple Task List Application
  • What to Debug & How to Debug
    • Debug React Native Application
Powered by GitBook
On this page
  • Installation
  • Browser Router
  • Route and Switch
  • Link
  • Dynamic Route Parameter

Was this helpful?

  1. Day 05

Next Stop - React Router | SPA

PreviousES6 Code ExamplesNextCode examples | Router

Last updated 5 years ago

Was this helpful?

React doesn't come with a built-in router, but we can easily achieve routing with the react-router-dom library. Routing is how a web applications direct traffic.

Example: If you go to dataworld.com, you end up on my home page. If you go to dataworld.com/me, you're redirected to my about me page. If you go to dataworld.com/categories/javascript or dataworld.com/categories/css, you end up on a category listing page. The routes for these pages look something like this:

  • / - root

  • /:page_id - page

  • /categories/:category_id - category

I'm not actually making a folder called categories and filling it with a bunch of files like javascript.html or css.html, I just have one template and the router knows to direct to the proper template. Once it gets to the template, it can pull from the URL to know which variables to display - for example, JavaScript or CSS related posts.

This website also happens to be a Single Page Application (or SPA) - only one page is loaded, and every click to a new page loads some additional JSON data, but does not actually request a new resource like loading index.html and about-me.html would.

I'm going to show you how to set up a simple SPA in React with react-router-dom, and pull in data dynamically through the URL. Below is the source of the completed project if you get lost along the way.

Prerequisites

Installation

Create a new React app.

npx create-react-app react-router-example
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

Our project has two dependencies - react-router-dom for the router, and axios for making API calls.

npm install react-router-dom axios

or

yarn add react-router-dom axios

Browser Router

  • BrowserRouter - makes pretty URLs like example.com/about.

  • HashRouter - makes URLs with the octothorpe (or hashtag, if you will) that would look like example.com/#about.

Let's use BrowserRouter.src/index.js

import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import App from './App'

render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.querySelector('#root')
)

Route and Switch

Now in App.js, we can decide on the routes we want to use and direct accordingly. We'll use Routeand Switch for this task.

  • Switch - Groups all your routes together, and ensures they take precedence from top-to-bottom.

  • Route - Each individual route.

App.js

import React from 'react'
import { Route, Switch } from 'react-router-dom'
// We will create these two pages in a moment
import HomePage from './pages/HomePage'
import UserPage from './pages/UserPage'

export default function App() {
  return (
    <Switch>
      <Route exact path="/" component={HomePage} />
      <Route path="/:id" component={UserPage} />
    </Switch>
  )
}

We're matching the root route (/) to HomePage, and dynamically matching any other page to UserPage. I only have one route for this simple example, but you could do more like this:

<Switch>
  <Route exact path="/" component={HomePage} />
  <Route path="/:id" component={UserPage} />
  <Route path="/categories" component={CategoriesPage} />
  <Route path="/categories/:id" component={IndividualCategoryPage} />
</Switch>

This would ensure that dataworld.com/categories would go to a page listing all categories, but dataworld.com/categories/javascript would go to a completely different template for the individual category listing.

Link

import React, { Component } from 'react'
import { Link } from 'react-router-dom'

export default function HomePage() {
  return (
    <div className="container">
      <h1>Home Page</h1>
      <p>
        <Link to="/taniarascia">taniarascia</Link> on GitHub.
      </p>
    </div>
  )
}

So now I'm going to my first route, the root route which is loading HomePage, and I see the content and the link.

Dynamic Route Parameter

Our Link is navigating to /dataworld, which will match the /:id parameter in Route. In order to dynamically get the content from the URL - in this case, taniarascia - we'll use match.params.idfrom the props.

import React, { useState, useEffect } from 'react'
import axios from 'axios'

export default function UserPage(props) {
  // Setting initial state
  const initialUserState = {
    user: {},
    loading: true,
  }

  // Getter and setter for user state
  const [user, setUser] = useState(initialUserState)

  // Using useEffect to retrieve data from an API (similar to componentDidMount in a class)
  useEffect(() => {
    const getUser = async () => {
      // Pass our param (:id) to the API call
      const { data } = await axios(`https://api.github.com/users/${props.match.params.id}`)

      // Update state
      setUser(data)
    }

    // Invoke the async function
    getUser()
  }, []) // Don't forget the `[]`, which will prevent useEffect from running in an infinite loop

  // Return a table with some data from the API.
  return user.loading ? (
    <div>Loading...</div>
  ) : (
    <div className="container">
      <h1>{props.match.params.id}</h1>

      <tab
        <tbody>
          <tr>
            <td>{user.name}</td>
            <td>{user.location}</td>
            <td>
              <a href={user.blog}>{user.blog}</a>
            </td>
            <td>{user.followers}</td>
          </tr>
        </tbody>
      </table>
    </div>
  )

Read or if you don't know React or React Hooks yet.

Read if you don't know how to work with APIs at all.

To use react-router-dom, we need to wrap our entire App component in . There are two types of routers:

In order to link to a page within the SPA, we'll use . If we used the traditional <a href="/route">, it would make a completely new request and reload the page, so we have Linkto help us out.src/pages/HomePage.js

router home page

I'm going to use that parameter to make a call to the GitHub API and retrieve my data. In this example I'll be using Hooks, so if you're not familiar with them, please read .src/pages/UserPage.js <props.match.params.id>

Getting Started with React
Build a React App with Hooks
How to Connect to an API in JavaScript
BrowserRouter
Link
Building a CRUD App with Hooks