Introduction About React History:
React history provides us with tools that help manage session history using React. This is a thin wrapper around the history package. In web browsers, this also helps in transparently managing the changes made to the URL and makes it easier for creators of single-page applications to support things like bookmarks and the back button.
Installation of React History:
Use the npm and run the code to install react npm:
$ npm install –save react-history
The next step is to use the module bundler like webpack like you would use any other pack:
// using ES6 modules
import { BrowserHistory } from ‘react-history’
// using CommonJS modules
var BrowserHistory = require(‘react-history’).BrowserHistory
The UMD that we build is also available on unpackage:
<script src=“https://unpkg.com/react-history/umd/react-history.min.js“></script>
The library can be found on: window.ReactHistory.
Usage of React History:
React-history runs with three different history components that you can choose to use depending on your environment.
– The first is <BrowserHistory> which is used in modern web browsers that support the HTML5 history API
– <MemoryHistory> is used as a reference implementation and may also be used in non-DOM environments like ReactNative
– <HashHistory> is for use in legacy web browsers.
Depending on which method you choose to use in order to keep track of history, you. Will import (or require) one of these methods directly from the package root (i.e. history/BrowserHistory). For the sake of brevity, the term <History> in this context refers to any of the implementations.
The basic usage of the function looks similar to this:
import History from ‘react-history/BrowserHistory’
const App = React.createClass({
render() {
return (
<History>
{({ history, action, location }) => (
<p>The current URL is {location.pathname}{location.search}{location.hash}. You arrived at this URL via a {action} action.</p>
)}
</History>
)
}
})
The props for each <History>, along with their default values are:
<BrowserHistory
basename=“” // The base URL of the app (see below)
forceRefresh={false} // Set true to force full page refreshes
keyLength={6} // The length of location.key
// A function to use to confirm navigation with the user (see below)
getUserConfirmation={(message, callback) => callback(window.confirm(message))}
/>
<MemoryHistory
initialEntries={[ ‘/’ ]} // The initial URLs in the history stack
initialIndex={0} // The starting index in the history stack
keyLength={6} // The length of location.key
// A function to use to confirm navigation with the user. Required
// if you return string prompts from transition hooks (see below)
getUserConfirmation={null}
/>
<HashHistory
basename=“” // The base URL of the app (see below)
hashType=“slash” // The hash type to use (see below)
// A function to use to confirm navigation with the user (see below)
getUserConfirmation={(message, callback) => callback(window.confirm(message))}
/>
Listening
The <History> element calls into play its children function every time the URL changes.
<History>
{({ history, action, location }) => (
<div>
<p>The current URL is {location.pathname}{location.search}{location.hash}.</p>
<p>You arrived at this URL via a {action} action.</p>
</div>
)}
</History>
The history object is the same object you’d get if you created your own history object directly.
The location and action properties represent the current URL and how we got there.
Navigation
React-history also provides the following components that may be used to modify the current URL:
– <Push> – It helps push a new entry onto the preexisting history stack
– <Replace> – It replaces the current entry on the history stack with a new one of your choice.
– <Pop>- This modifies the current pointer or index into the already existing history stack.
– <Back>- It moves backward one entry on the History stack, shorthand for the command <Pop go={-1}/>
– <Forward> it moves forward one entry in the history, shorthand for <Pop go={1}/>
All these components are called “action” components simply because they modify the URL. When any of these are rendered, the URL updates and <History> objects emit a new location.
<Push> and <Replace> accept one of two props:
– A path and state props
Or
– A location prop.
// Push a new entry onto the history stack.
<Push path=“/home?the=query#the-hash” state={{ some: ‘state’ }}/>
// Use a location-like object to push a new entry onto the stack.
<Push location={{
pathname: ‘/home’,
search: ‘?the=query’,
hash: ‘#the-hash’
state: { some: ‘state’ }
}}/>
It is important to note that the location state is not supported while using <HashHistory>.
For example, you could build a very simple <Link> component using a <Push>:
import React, { PropTypes } from ‘react’
import { Push } from ‘react-history/Actions’
const Link = React.createClass({
propTypes: {
to: PropTypes.string.isRequired
},
getInitialState() {
return { wasClicked: false }
},
render() {
const { to, …props } = this.props
// If the <Link> was clicked, update the URL!
if (this.state.wasClicked)
return <Push path={to}/>
return (
<span {…props} onClick={() => this.setState({ wasClicked: true })}/>
)
}
})
The <link> implementation is only for demonstration purposes. It is not accessible and does not include many of the nice features of a real hyperlink. If you’re looking for a proper <Link> implementation, you can use the react-router.
Blocking Transitions
React-history lets you register a prompt message that will be shown to the user before location listeners are notified. This allows you to make sure the user wants to leave the current page before they navigate away. This is done by rendering the <Prompt> component.
import Prompt from ‘react-history/Prompt’
const Form = React.createClass({
getInitialState() {
return { inputText: ” }
},
handleChange(event) {
this.setState({ inputText: event.target.value })
},
render() {
const { inputText } = this.state
return (
<form>
<Prompt
message=“Are you sure you want to leave before submitting the form?”
when={inputText}
/>
<input
type=“text”
defaultValue={inputText}
onChange={this.handleChange}
/>
</form>
)
}
})
Again, it is important to note that you will need to provide a getUserConfirmation prop to use <Prompt> with <MemoryHistory>.
Using a Base URL
If all URLs in your app are relative to some other base URL, the basename option can be used. This option allows you to transparently add the given string to the front of all the URLs you use.
// All URLs transparently have the “/the/base” prefix.
<History basename=“/the/base”>
{({ location }) => (
// When the URL is /the/base/home, location.pathname is just /home.
<p>The current pathname is {location.pathname}.</p>
)}
</History>
Note: Basename is not supported on <MemoryHistory> where you have full control over all your URLs.
Forcing Full Page Refreshes in <BrowserHistory>
By default, <BrowserHistory> uses HTML5 pushState and replaceState in order to prevent the reloading of the entire page from the server whilst navigating around. If instead, you would like to reload as the URL changes, use the forceRefresh option.
<BrowserHistory forceRefresh/>
Modifying the Hash Type in <HashHistory>
By default, <HashHistory> uses a leading slash in hash-based URLs. You can use the hash type option to use a different hash formatting.
// The default is to add a leading / to all hashes, so your URLs
// are like /#/inbox/5. This is also known as the “slash” hash type.
<HashHistory hashType=“slash”/>
// You can also omit the leading slash using the “noslash” hash type.
// This gives you URLs like /#inbox/5.
<HashHistory hashType=“noslash”/>
// Support for Google’s legacy AJAX URL “hashbang” format gives you
// URLs like /#!/inbox/5.
<HashHistory hashType=“hashbang”/>