Explain Codes LogoExplain Codes Logo

Programmatically navigate using React router

javascript
react-router
navigation
hooks
Anton ShumikhinbyAnton Shumikhin·Aug 13, 2024
TLDR

To change routes in your application, use the useNavigate hook in React Router v6. Invoke the navigate(PATH) with your desired path.

import { useNavigate } from 'react-router-dom'; function NavigateButton() { const navigate = useNavigate(); const handleNavigation = () => { navigate('/destination'); // Like a GPS, navigate() leads us right to the '/destination' }; return <button onClick={handleNavigation}>Go</button>; }

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.

import { withRouter } from 'react-router-dom'; class MyComponent extends React.Component { navigateToProfile = () => { this.props.history.push('/profile'); // Hop on the '/profile' express, no ticket necessary! } render() { return <button onClick={this.navigateToProfile}>Go to Profile</button>; } } export default withRouter(MyComponent);

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') into useNavigate.
  • Substituting withRouter for hooks while refactoring.
  • Following the official upgrade guides during major version shifts.
  • Upgrading from browserHistory to relaxed useNavigate.

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:

// history.js import { createBrowserHistory } from 'history'; export default createBrowserHistory();

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.