Angular icon Get $100 off the 7-Courses Angular Master Bundle!

See the bundle then add to cart and your discount is applied.

days
hours
mins
secs
  • Blog
  • React
  • Programmatically navigate with React Router (and Hooks)

Programmatically navigate with React Router (and Hooks)

May 22, 2020 3 mins read

React post

In this post you’ll learn how programmatically navigate with React Router v5+ and the new useHistory hook!

To programmatically navigate means to use JavaScript, i.e. program code, a function or method call. If you just want a straight-up hyperlink then your best bet is <Link to="/some-url" />, otherwise here we go!

This post will answer questions like “How can I navigate on a click event in React?” or “What do I use to navigate inside a React component?”.

Assuming you’re working in the DOM, you’ll want to ensure you’ve npm install react-router-dom - I’m using React Router 5.2.0 and React 16.13.1.

Let’s get React Router setup, I’m importing components Hello and Goodbye to demonstrate how to handle history with hooks!

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import Hello from './Hello';
import Goodbye from './Goodbye';

const App = () => (
  <Router>
    <Route exact path="/" component={Hello} />
    <Route path="/goodbye" component={Goodbye} />
  </Router>
);

render(<App />, document.getElementById('root'));

Using React Router’s “useHistory” hook

Introduced in React Router 5.1.0, the useHistory hook is considered the new and future-facing direction for interacting with the history package from the great folks at React Training. Their history implementation is one of two dependencies to React Router (the other being React) which promotes a really clean API surface.

Exploring JavaScript Array Methods cover

⚡️ FREE eBook: 🔥 ForEach, Map, Filter, Reduce, Some, Every, Find

Todd Motto “This book is straight to the point, syntax exploration, comprehensive guide, real-world examples, tips and tricks - it covers all you need” Todd Motto, author of Exploring JavaScript Array Methods

Then, inside our Hello component, we’ll import the useHistory hook from React Router - I’m also setting this up nicely with an onClick handler:

import React from 'react';
import { useHistory } from 'react-router-dom';

const Hello = () => {
  const history = useHistory();
  const handleClick = () => history.push('/goodbye');
  
  return (
    <button type="button" onClick={handleClick}>
      Goodbye
    </button>
  );
};

export default Hello;

Clean, right? Inside the functional component we simply instantiate the useHistory hook.

Check out the Stackblitz example below which demonstrates this new hooks approach:

But it’s not always been this way - before hooks came the history prop and React classes…

The “history” prop (legacy)

Now that the useHistory hook exists, it would be a sensible time to stop using the history prop as it would only work if our component is a component passed to the <Route /> component.

The beauty of the useHistory hook is that it can be used in any component!

What is the history prop? If you check back to our code earlier, we had this:

const App = () => (
  <Router>
    <Route exact path="/" component={Hello} />
    <Route path="/goodbye" component={Goodbye} />
  </Router>
);

Our Route definitions are part of React Router, and when React Router renders it supplies a component 3 extra props - history, location and match.

We haven’t yet seen our Goodbye component, maybe we could create it in the legacy style using a class and the history prop:

import React, { Component } from 'react';

class Goodbye extends Component {
  handleClick() {
    this.props.history.push('/');
  }
  render() {
    return (
      <button type="button" onClick={() => this.handleClick()}>
        Hello
      </button>
    );
  }
};

export default Goodbye;

You can see that both Hello and Goodbye components work flawlessly together, so this could be something you can migrate in phases perhaps:

Summary

We’ve covered a lot of ground here for something so simple, but I feel we’ve effectively explored our options. To recap:

  • Use the useHistory hook for new projects (our Hello component)
  • Refactor existing history prop approaches (our Goodbye component)
Exploring JavaScript Array Methods cover

⚡️ FREE eBook: 🔥 ForEach, Map, Filter, Reduce, Some, Every, Find

Todd Motto “This book is straight to the point, syntax exploration, comprehensive guide, real-world examples, tips and tricks - it covers all you need” Todd Motto, author of Exploring JavaScript Array Methods

I hope you enjoyed the post, and if you’d love to learn more please check out the React courses we’re working on where you’ll learn everything you need to know to be extremely good and proficient at React and the surrounding ecosystem, hooks and beyond!

Happy coding!

You'll also like...