reacttraining / react-history Goto Github PK
View Code? Open in Web Editor NEWManage session history with React
Manage session history with React
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."
)
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 value of the basename
prop should:
location.pathname
before emitting location changes andThis feature lets us support "mounting" apps at different URL prefixes while hiding that portion of the URL from downstream code.
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
.
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.
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.
Hi,
It would be cool to stop using React.PropTypes (which is deprecated) in favor of the dedicated package prop-types.
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.
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.
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!
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.
Using
import { Push } from "react-history/Actions";
Error
TypeError: Cannot read property 'oneOf' of undefined
8 | var action = exports.action = _react.PropTypes.oneOf(['PUSH', 'REPLACE', 'POP']);
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.