Programmatically navigate using React router
To change routes in your application, use the useNavigate
hook in React Router v6. Invoke the navigate(PATH)
with your desired path.
In this example, navigate()
is our GPS, leading us to new addresses in our app without the need for a hitchhiking <Link>
.
Classic Class Components
Still rocking class components? Inject some navigational magic with withRouter
and history.push()
. Your life jacket is props.history
.
FYI: withRouter
is an old pal from v4 and it's not hanging out with the cool kids in v6.
The Great Migration
Adapting to changing times might involve:
- Turning
this.props.history.push('/path')
intouseNavigate
. - Substituting
withRouter
for hooks while refactoring. - Following the official upgrade guides during major version shifts.
- Upgrading from
browserHistory
to relaxeduseNavigate
.
Paging History! Are You There?
Get to grips with the history object:
history.push('/path')
is your time-travel machine in v4, taking you to new lands.history.replace('/path')
is your eraser, leaving no trace of past visits.- Custom history objects offer a Swiss Army Knife of navigational tools in v4.
All Aboard The EventHandler
Control navigation flow using event handlers:
- Redirect following form submissions or upon button clicks.
- Navigate after asynchronous actions, like fetching data.
- Guard routes to deflect unauthorized intruders.
Sharing Is Caring
In complex apps, consider a shared history object:
This modular approach grants programmatic control of navigation but is no longer en vogue in v6.
Sneaky Navigation: Automatic Triggers
Sometimes, navigation needs an invisible hand:
- Redirect after a list item gets the axe.
- Automate navigation in response to state changes.
- Reroute traffic upon authentication changes.
Was this article helpful?