Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs with history

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!

like image 482
Heptic Avatar asked Jan 13 '14 22:01

Heptic


People also ask

Why history is used in react?

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.

How do I get route history in react?

Provider value={{ history, user }}> <Switch> <Route exact path="/" render={(props) => <Home {... props} />} /> <Route exact path="/sign-up" render={(props) => <SignUp {... props} setUser={setUser} />} /> ...

Is useHistory deprecated?

The use of history and useHistory is deprecated and should be replaced with the useNavigate hook.


2 Answers

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.

like image 108
Matt Moriarity Avatar answered Oct 04 '22 14:10

Matt Moriarity


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

like image 21
user3317868 Avatar answered Oct 04 '22 16:10

user3317868