I am trying to handle history with reactjs, in such a way that the browser back and forward buttons work intuitively. Is there any examples of this, or general guidelines I should be following?
Thanks!
It lets you access the history instance used by React Router. Using the history instance you can redirect users to another page. The history instance created by React Router uses a Stack( called “History Stack” ), that stores all the entries the user has visited.
Provider value={{ history, user }}> <Switch> <Route exact path="/" render={(props) => <Home {... props} />} /> <Route exact path="/sign-up" render={(props) => <SignUp {... props} setUser={setUser} />} /> ...
The use of history and useHistory is deprecated and should be replaced with the useNavigate hook.
It's not too much different than how you would handle history without React.js. What works well for me is this: I have a top-level component that holds the state of the app in this.state
. I'm using Backbone's router, so when I get an event from the router (a URL was loaded or changed in some way), I call setState
to update the top-level component's state. When I update the state myself, I make sure to also call the router's navigate method to update the URL. Seems to work pretty well: you can see an example from my little app at https://github.com/mjm/eats.
Another option with React is to use the React router component. It handles pushState for you and you can dynamically change the available routes as needed. It works with the same methodology as React does, as it is a react class itself. Check it out at:
https://www.npmjs.org/package/react-router-component
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With