Giter Site home page Giter Site logo

react-history's Introduction

react-history Travis npm package

react-history provides tools to manage session history using React. It's a thin wrapper around the history package. In web browsers, this library also transparently manages changes to the URL which makes it easier for creators of single-page applications to support things like bookmarks and the back button.

Note: This library is highly experimental.

Installation

Using npm:

$ npm install --save react-history

Then with a module bundler like webpack, use as you would anything else:

// using ES6 modules
import { BrowserHistory } from "react-history";

// using CommonJS modules
var BrowserHistory = require("react-history").BrowserHistory;

The UMD build is also available on unpkg:

<script src="https://unpkg.com/react-history/umd/react-history.min.js"></script>

You can find the library on window.ReactHistory.

Usage

react-history ships with 3 different history components that you can use depending on your environment.

  • <BrowserHistory> is for use in modern web browsers that support the HTML5 history API (see cross-browser compatibility)
  • <MemoryHistory> is used as a reference implementation and may also be used in non-DOM environments, like React Native
  • <HashHistory> is for use in legacy web browsers

Depending on the method you want to use to keep track of history, you'll 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 document refers to any of these implementations.

Basic usage looks like 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

<History> elements call their 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. Please refer to the history docs for more information on how to use it.

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> pushes a new entry onto the history stack
  • <Replace> replaces the current entry on the history stack with a new one
  • <Pop> modifies the current pointer or index into the history stack
  • <Back> moves back one entry in the history, shorthand for <Pop go={-1}/>
  • <Forward> moves forward one entry in the history, shorthand for <Pop go={1}/>

These components are called "action" components 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 either:

  • 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' }
}}/>

Note: Location state is not supported using <HashHistory>.

For example, you could build a very simple <Link> component using a <Push>:

import React from "react";
import PropTypes from "prop-types";
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 })} />
    );
  }
});

Note: This <Link> implementation is for demonstration purposes only. 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, please use 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. You do this by rendering a <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>
    );
  }
});

Note: You'll need to provide a getUserConfirmation prop to use <Prompt>s with <MemoryHistory> (see the history docs).

Using a Base URL

If all the URLs in your app are relative to some other "base" URL, use the basename option. This option transparently adds the given string to the front of all 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 suppported in <MemoryHistory> where you have full control over all your URLs.

Forcing Full Page Refreshes in <BrowserHistory>

By default <BrowserHistory> uses HTML5 pushState and replaceState to prevent reloading the entire page from the server while 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 hashType 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 know 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"/>

Thanks

Thanks to BrowserStack for providing the infrastructure that allows us to run our build in real browsers.

react-history's People

Contributors

cheshireswift avatar greenkeeperio-bot avatar mjackson avatar ryanflorence avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-history's Issues

Actions are not declarative

First off, thanks for the great work on the lib.

We have a case where we want to use <Push /> within our components to pushState on tabs change (click to the next active tab). A colleague of mine rightly pointed out that even though we're rendering the push action, we're not really declaring the app state. The reason is that the action component will not change the app state back when it unmounts....

Take this for example:

render() { return this.state.newActiveTab === 'foo' ? <Push path="/foo" /> : null; }.

The correct behavior one would assume, is to "pop" the action when the condition evaluates as false in the above scenario.

We tried to think whether calling history.pop() on cWU would do it, but there can be side effects since other history actions may have been performed by then...

This isn't react-history's fault, rather one related to the stateful history API. Which means we'd have to set <Push path="/" /> both initially on the page (to keep up with URL state), as well as a the default component to render each time we want to go back to the default tab.

We decided action components were a bad idea and opted for creating a HOC instead:

import React, { Component } from 'react';
import { history as historyType } from './PropTypes';
import wrapDisplayName from 'recompose/wrapDisplayName';
import hoistStatics from 'hoist-non-react-statics';
import pick from 'lodash/pick';

export default (WrappedComponent) => {
    class WithHistoryActions extends Component {
        static displayName = wrapDisplayName(
            WrappedComponent,
            'withHistoryActions',
        );

        static contextTypes = {
            history: historyType,
        };

        historyActions = pick(this.context.history, [
            'push',
            'replace',
            'go',
            'goBack',
            'goForward',
            'block',
        ]);

        render() {
            return (
                <WrappedComponent
                    {...this.props}
                    history={this.historyActions}
                />
            );
        }
    }

    return hoistStatics(WithHistoryActions, WrappedComponent);
};

ps: a possible workaround if we want to keep Actions.js is to save the initial location value of createBrowserHistory() in memory and use it to go to that history step when any action component unmounts.

history.push redirects to requested url but does not render related component

Hello Sir

I have below routing in app function:

<Route exact path="/" component={ListOfItems}></Route>
<Route path="/list/:searchquery?" component={ListOfItems}></Route>

second Route is working well when i pass any search term but when i try to access first route '/' using history.push('/') calling by function it changes the url in the browser but does not render the component of '/' route.

import { createBrowserHistory } from "history";
const history = createBrowserHistory();

const redirectToHome = () => {
    history.push('/');
  }

could you please suggest me what is the issue? Thanks a lot.

Upgrading to react 16

Hello! I was wondering if there was a timeline for upgrading this component to react 16?

I tried doing it myself but ran into an issue where I couldnt get all of the tests passing. Its the same issue that is causing the build to currently fail. The file modules > __tests__ > RenderTestSequences > ReplaceChangesTheKey.js is causing the tests to fail. This is the output of the CI build that is failing:

Error: Expected { pathname: '/', search: '', hash: '', state: undefined, key: '0hx5id' } to match { pathname: '/', key: undefined }
	   at assert (webpack:///~/expect/lib/assert.js:29:0 <- tests.webpack.js:25858:4)
	   at toMatch (webpack:///~/expect/lib/Expectation.js:138:0 <- tests.webpack.js:23296:9)
	   at Anonymous function (webpack:///modules/__tests__/RenderTestSequences/ReplaceChangesTheKey.js:11:6 <- tests.webpack.js:28189:7)
	   at Anonymous function (webpack:///modules/__tests__/RenderTestSequences/createRenderProp.js:12:6 <- tests.webpack.js:27467:8)
	   at render (webpack:///modules/MemoryHistory.js:52:4 <- tests.webpack.js:29130:6)
	   at Anonymous function (webpack:///~/react-dom/lib/ReactCompositeComponent.js:793:0 <- tests.webpack.js:16402:10)
	   at measureLifeCyclePerf (webpack:///~/react-dom/lib/ReactCompositeComponent.js:73:0 <- tests.webpack.js:15682:6)
	   at _renderValidatedComponentWithoutOwnerOrContext (webpack:///~/react-dom/lib/ReactCompositeComponent.js:792:0 <- tests.webpack.js:16401:8)
	   at _renderValidatedComponent (webpack:///~/react-dom/lib/ReactCompositeComponent.js:819:0 <- tests.webpack.js:16428:10)
	   at performInitialMount (webpack:///~/react-dom/lib/ReactCompositeComponent.js:359:0 <- tests.webpack.js:15968:8)

The problem is that the location object provided to the first step does not match the expected location object. If this is solved I think upgrading to react should be pretty easy to do. Also if youre too busy to take a look at this, then I can continue to dig around history to figure out why this initial location object changed if you point me in the right direction.

Thanks!

Add <History basename>

The value of the basename prop should:

  • be stripped from the beginning of location.pathname before emitting location changes and
  • be added to the beginning of a path before updating the URL

This feature lets us support "mounting" apps at different URL prefixes while hiding that portion of the URL from downstream code.

Add <Prompt when>

The <Prompt when> prop makes the prompt active only when its value is true. So instead of doing this:

{condition && <Prompt ...>}

users can do this:

<Prompt when={condition} ...>

and avoid the conditional rendering.

The history prop is undefined

I was using version 0.13.3 of this package in my project. It was working fine, but I decided to upgrade to the latest (0.18.2) and that broke it. When I first load the page, the history prop is undefined.

<History basename={basename} keyLength={keyLength}>
	{({ history, action, location }) => {
		// history is undefined here
		return (
			<DispatchingRouter
				store={this.context.store || this.props.store}
				history={history}
				action={action}
				location={location}
				basename={basename}
				{...props}
			/>
		);
	}}
</History>

I've ended up reverting back to 0.13.3 for now.

Add <Prompt beforeUnload> ?

We need the ability to prevent navigation in case the user decides to refresh the page. I was thinking we could do this w a <Prompt beforeUnload> prop that might be used in lieu of a message prop.

Related: Custom beforeunload messages are removed in Chrome 51. We should probably warn if someone tries to use both beforeUnload and message.

Using with redux-saga

Currently, the <History> component expects a createHistory function and a historyOptions object, which it uses to create a history object. Would it be feasible to add a history prop to the component that takes a history object provided by the user?

When it is detected in the setupHistory method, it could be set instead of creating a new history object.

setupHistory() {
  const { history, createHistory, historyOptions } = this.props
  this.history = history ? history : createHistory(historyOptions)
  this.unlisten = this.history.listen(() => this.forceUpdate())
}

There are issues for some users using react-router v4 where they want to do navigation outside of components (e.g., using redux-saga), but because the history object is created within the <History> component, they do not have a good way to access it. This issue would be solved if they could create the history object that would be used by the application.

Warn when pathname does not contain basename

Given a history with a basename:

const history = createBrowserHistory({ basename: '/base' })

When the history gets the location from the URL, it will strip the basename off of the pathname.

if (basename)
  path = stripPrefix(path, basename)

This means that a pathname without the basename is treated the same as a pathname with the basename.

"/base/my-page" == "/my-page"

It could be argued that this problem exists only when a user is improperly creating the history (you should only create a history with a basename when you are on a page with that basename), but at the very least I think that a warning would be helpful.

warning(
  !(basename && pathname.indexOf(basename) !== 0),
  "You are attempting to use a basename on a page whose URL has no basename."
)

Usage of <Push />, <Pop />,...

Hi @mjackson,

I'm a bit embarrassed to ask you that, maybe I'm taking the problem in the wrong way.
I'm trying to use the <Push /> component after clicking on one of my menu items.
When I see this in react-history docs, I don't really get that part:

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 <Push /> component gets rendered and the previous menu span disappears.

This may be ridiculous, but I'm guessing on what is the proper pattern to use a component like this, which has a one-shot action (and should be destroyed ?)?
Putting it in an another component, which I will destroy after the behaviour done?

Maybe it will help somebody else who is struggling like me.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.