For a consistent user experience, I'd like my react app to reverse its state when the user clicks the browser back button.
For example, if I change an element in the state with a function call:
changeVar = (idx) => (event) => {
this.setState({thisIndex: idx});
//how to notify browser stack of this change?
}
How could I add this to the browser stack so that users can click the back button in the browser to reverse the state change?
For a consistent user experience, I'd like my react app to reverse its state when the user clicks the browser back button.
For example, if I change an element in the state with a function call:
changeVar = (idx) => (event) => {
this.setState({thisIndex: idx});
//how to notify browser stack of this change?
}
How could I add this to the browser stack so that users can click the back button in the browser to reverse the state change?
Share Improve this question asked May 20, 2018 at 15:24 bearbear 6631 gold badge15 silver badges34 bronze badges 1- 2 If you are using redux (and you probably should if you aren't), the topic is covered [here][1] [1]: redux.js/recipes/implementing-undo-history – Barazu Commented May 20, 2018 at 20:20
1 Answer
Reset to default 4So in general question is "how could I handle browser Back/Next button clicked?" or "How could I react on user navigates through history?"
Here such a thing like History API with its .pushState
es to the scene.
In short:
- on each significant state change you call
history.pushState(stateData)
- once user clicks Back button it does not actually navigate away to different URL rather change current state only(but only if previous state in the stack has been created with
.pushState
or.replaceState
) - your code detects if history navigation occurs(Back button been clicked) by listening to popstate event
- based on appropriate state data that you read from
history.state
you restore application state appropriately
So far the last question is how to put all the data across your application in single object and to restore all the application with it modules' states later. And here redux es to the help. Redux suppose you have just single Store over all your application. In other words all the state is already contained in single object that you just need to pass into .pushState()
to store and to restore it after Back button is clicked.
PS remember I told about significant change? since "all the data all over the application" is large enough it would make overhead to store store it million times in the memory. Also it would be a silly if clicking Back button say just collapse a dropdown.
PPS and since history
is global there is no way to store/restore state on per-ponent way. so maybe(just maybe) it's better to implement something like "state change history" for your ponent and propose user some different control to restore its state(instead of clicking Back button in browser)