Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Desmond Nyamador

Using React with the History API

Desmond Nyamador

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

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:

1yarn add react-router-dom
bash

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

1import React from "react";
2
3function HomePage() {
4    return <p>Welcome Home</p>;
5}
6function About() {
7    return <p>About Page</p>;
8}
9function Contact() {
10    return <p>Contact Page</p>;
11}
12function Foo() {
13    return <p>Contact Bar</p>;
14}
15
16export {HomePage, About, Contact, Foo};
jsx
1# Routes
2import React from "react";
3import { Route, Switch , BrowserRouter as Router} from "react-router-dom";
4import { HomePage, About, Contact, Foo } from "./Pages/Homepage";
5import "./global.css";
6
7const Routes = () => {
8    return (
9				<Router>
10            <Switch>
11                <Route exact path="/" component={HomePage} />
12				</Router>
13        </div>
14    );
15};
16
17export 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.

1import React from "react";
2import { useHistory } from "react-router-dom";
3
4function HomePage() {
5    const history = useHistory();
6
7    return (
8        <>
9            <button
10                onClick={() => history.push("/about", { from: "HomePage" })}
11            >
12                About
13            </button>
14            <button
15                onClick={() => history.push("/contact", { from: "HomePage" })}
16            >
17                Contact
18            </button>
19            <p>Welcome Home</p>
20        </>
21    );
22}
23function About({ location }) {
24    const history = useHistory();
25    return (
26        <>
27            <p>About Page </p>
28            <button
29                onClick={() => {
30                    history.goBack();
31                }}
32            >
33                Go back
34            </button>
35            <p> You were redirected from {location.state.from}</p>
36        </>
37    );
38}
39function Contact({ location }) {
40    const history = useHistory();
41    return (
42        <>
43            <p>Contact Page</p>
44            <button
45                onClick={() => {
46                    history.goBack();
47                }}
48            >
49                Go back
50            </button>
51            <p>You were redirected from {location.state.from}</p>
52        </>
53    );
54}
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.

1import React from "react";
2
3import { useHistory } from "react-router-dom";
4
5function HomePage() {
6    const history = useHistory();
7
8    return (
9        <>
10            <button
11                onClick={() => history.push("/about", { from: "HomePage" })}
12            >
13                About
14            </button>
15
16            <button
17                onClick={() => history.push("/contact", { from: "HomePage" })}
18            >
19                Contact
20            </button>
21
22            <p>Welcome Home</p>
23        </>
24    );
25}
26
27function About({ location }) {
28    const history = useHistory();
29
30    console.log(history);
31
32    return (
33        <>
34            <p>About Page </p>
35
36            <button
37                onClick={() => {
38                    history.goBack();
39                }}
40            >
41                Go back
42            </button>
43
44            <p> You were redirected from {location.state.from}</p>
45        </>
46    );
47}
48
49function Contact({ location }) {
50    const history = useHistory();
51
52    return (
53        <>
54            <p>Contact Page</p>
55
56            <button
57                onClick={() => {
58                    history.goBack();
59                }}
60            >
61                Go back
62            </button>
63
64            <p>You were redirected from {location.state.from}</p>
65        </>
66    );
67}
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.

Learn More

Explore these React courses from Pluralsight to continue learning: