Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Using React with the History API

Sep 17, 2020 • 7 Minute Read

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

From React Router Documentation

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:

      yarn add react-router-dom
    

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

      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};
    
      # 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;
    

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.

      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>
        </>
    );
}
    

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.

      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>
        </>
    );
}
    

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: