React-router go back a page how do you configure history?
useHistory
, a hook provided by React Router, can be used to navigate back through history.goBack()
.
Press the Go Back button and voila! You're on the previous page.
Transition to useHistory in newer version
The more recent versions of React Router, especially v6, useNavigate
replaces useHistory
.
In single-page apps, calling navigate(-1)
would mimic history.goBack()
. Time travel made easy, isn't it? 😂
Navigation in class components
No hooks allowed in a class component party? Not to worry. The withRouter
high-order component presents the history object:
Like a backstage pass at a concert, withRouter gives you access to all the good stuff.
Taking care of direct route access
In scenarios where users land directly on a page (say, via a bookmark or external link), a Go Back action could literally take them back to where they came from (yes, even to that e-commerce site where they last checked out dog food). Remember to have a fallback plan:
Checking history state
Always be sure that the history state is in check. Especially when dealing with iframe scenarios, where browser history might be either isolated or non-existent.
Ensuring compatibility with React Suspense
Planning an upgrade to React Suspense or Concurrent mode? Ensure your history interactions are cool with the asynchronous workings of these more advanced features. Most of this tops talking about navigation actions as side effects.
Boasting ES6 and default exports
Show off your ES6 syntax skills for cleaner and more readable code. And keep the default exports in mind when you can.
Making UX a bliss with Button History Navigation
A back button with clear history navigation is a major UX win. It's like breadcrumbs for the user, but digital and definitely not edible.
- Button Highlight: Enemies spotted with
onMouseOver
. - Tooltip Info: PS5 restock not guaranteed:
title="Go back to the previous page"
. - Button Unavailable: No breadcrumbs (history) left:
disabled={!history.length}
.
Advance Moves with React Router Patterns
Make use of advanced patterns for more granular control over back navigation:
- Nested Routes: For those inception moments, nested routes provide relative navigation.
- Auth Guards: Stop users from going back to protected pages, even after logout. "Access Denied!"
- Custom Hooks: Can't get enough of hooks? Create a
useBackNavigation
hook for reuse and cleaner components.
The Dirty Details (or Edge Cases)
- Detecting the end: Use
history.length
to decide to show the back button. Like a spoiler alert but for transitions. - Stay Put: Avoid accidental detours with
event.preventDefault()
. - 404 handling: Ensure users can always turn back if they reach the dreaded 404 page.
Was this article helpful?