Reputation: 3498
I have an application that has a list of employees as a part of it. When the user clicks on an employee, the app navigates to the details page of the employee. In the details page there is a button that executes history.goBack()
, which would take the user to the employee list, but that is not the only way to navigate to the employee list in the app.
I need to execute certain logic only when the user has gotten to the employee list by using history.goBack
(the logic should NOT be executed, when the user gets to the employee list, f.e. using history.push
).
How can I detect whether the user got there by using history.goBack() in the employee list component?
Upvotes: 1
Views: 534
Reputation: 29277
You can use the history.action
prop. After goBack
is POP
while after replace is PUSH
or REPLACE
.
https://reactrouter.com/web/api/history
Notice that the action
is also POP
on first load. If you want to ignore this case, combine it with history.length > 1
.
To summarize:
const isBack = history.action === "POP" && history.length > 1;
https://codesandbox.io/s/react-router-dom-identify-goback-1po29?file=/src/pages/Project.js (Click on "About" and "Back")
Upvotes: 0
Reputation: 9354
Presumably you also need to run this logic when the user clicks the built in browser "back" button, since this is functionally identical? The short answer is, you can't. The browser has no built in events for navigation direction by design for security reasons.
What you can do instead is create a HOC or Hook which calls history.listen
and continuously updates some piece of state with the previous location. Then provide it as Context to the relevant components and compare it where needed with the current location.
This is probably a better solution anyway since it sounds like you only want to run logic in this limited routing scenario, and listening to a generalised "back" event would make it prone to errors should you add more ways to route back to the Employee List in the future.
Upvotes: 1