Author avatar

Desmond Nyamador

Using React with the History API

Desmond Nyamador

  • Sep 17, 2020
  • 7 Min read
  • 688 Views
  • Sep 17, 2020
  • 7 Min read
  • 688 Views
Web Development
Front End Web Development
Client-side Frameworks
React

Introduction

Routing in React makes extensive use of the HTML5 History API. In this guide, you'll be introduced to the History API and build a simple app to gain a solid understanding of how it works while making use of the React router package.

Understanding the History API

The majority of browsers currently expose a history object on the DOM's Window object, which is used to access the browser's session history and navigate foward and backwards using the history.back() and history.forward() methods (which also function like the back and forward buttons in the browser), and many other methods such as go() and pushState(). You can read more on the HTML5 History API via the Mozilla Developer Network (MDN) documentation .

React Router uses the history package, which builds on the browser history API to provide an interface to which we can use easily in React apps.

The history object has the following properties and methods:

  • length - (number) The number of entries in the history stack
  • action - (string) The current action (PUSHREPLACE, or POP)
  • location - (object) The current location. May have the following properties:
    • pathname - (string) The path of the URL
    • search - (string) The URL query string
    • hash - (string) The URL hash fragment
    • state - (object) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
  • push(path, [state]) - (function) Pushes a new entry onto the history stack
  • replace(path, [state]) - (function) Replaces the current entry on the history stack
  • go(n) - (function) Moves the pointer in the history stack by n entries
  • goBack() - (function) Equivalent to go(-1)
  • goForward() - (function) Equivalent to go(1)
  • block(prompt) - (function) Prevents navigation

Set Up Development Environment

Set up your environment to build out a simple app that acts as a dummy browser and has a tiny analytics solution to show which pages users are coming from. You can either use create-react-app on your local machine or type react.new in your browser to have a fully configured react environment via codesandbox.io .

Next, add react-router as a dependency in your terminal with the command below:

1
yarn add react-router-dom
bash

Set up dummy pages and routes that render simple text based components.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from "react";

function HomePage() {
    return <p>Welcome Home</p>;
}
function About() {
    return <p>About Page</p>;
}
function Contact() {
    return <p>Contact Page</p>;
}
function Foo() {
    return <p>Contact Bar</p>;
}

export {HomePage, About, Contact, Foo};
jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Routes
import React from "react";
import { Route, Switch , BrowserRouter as Router} from "react-router-dom";
import { HomePage, About, Contact, Foo } from "./Pages/Homepage";
import "./global.css";

const Routes = () => {
    return (
				<Router>
            <Switch>
                <Route exact path="/" component={HomePage} />
				</Router>
        </div>
    );
};

export default Routes;
jsx

The useHistory Hook

React Router has a useHistory hook that provides a history interface that we can easily use for routing. Add buttons to these pages as shown below to add routing with the History API.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import React from "react";
import { useHistory } from "react-router-dom";

function HomePage() {
    const history = useHistory();

    return (
        <>
            <button
                onClick={() => history.push("/about", { from: "HomePage" })}
            >
                About
            </button>
            <button
                onClick={() => history.push("/contact", { from: "HomePage" })}
            >
                Contact
            </button>
            <p>Welcome Home</p>
        </>
    );
}
function About({ location }) {
    const history = useHistory();
    return (
        <>
            <p>About Page </p>
            <button
                onClick={() => {
                    history.goBack();
                }}
            >
                Go back
            </button>
            <p> You were redirected from {location.state.from}</p>
        </>
    );
}
function Contact({ location }) {
    const history = useHistory();
    return (
        <>
            <p>Contact Page</p>
            <button
                onClick={() => {
                    history.goBack();
                }}
            >
                Go back
            </button>
            <p>You were redirected from {location.state.from}</p>
        </>
    );
}
jsx

The snippet above uses the goBack() method to mimic the back button in the browser and the push() method to move to a new route. The push() method also takes a state object as well with from as a property.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import React from "react";

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

function HomePage() {
    const history = useHistory();

    return (
        <>
            <button
                onClick={() => history.push("/about", { from: "HomePage" })}
            >
                About
            </button>

            <button
                onClick={() => history.push("/contact", { from: "HomePage" })}
            >
                Contact
            </button>

            <p>Welcome Home</p>
        </>
    );
}

function About({ location }) {
    const history = useHistory();

    console.log(history);

    return (
        <>
            <p>About Page </p>

            <button
                onClick={() => {
                    history.goBack();
                }}
            >
                Go back
            </button>

            <p> You were redirected from {location.state.from}</p>
        </>
    );
}

function Contact({ location }) {
    const history = useHistory();

    return (
        <>
            <p>Contact Page</p>

            <button
                onClick={() => {
                    history.goBack();
                }}
            >
                Go back
            </button>

            <p>You were redirected from {location.state.from}</p>
        </>
    );
}
jsx

Conclusion

You've successfully gone through the basics of using the History API via React Router. You can read more on React Router via the documentation. You can reach me on Twitter as well at @DesmondNyamador.

2