9

Programmatically Navigate Using React Router and Hooks

 3 years ago
source link: https://typeofnan.dev/programmatically-navigate-using-react-router-5-and-hooks/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

TypeOfNaN

Programmatically Navigate Using React Router and Hooks

Nick Scialli • May 23, 2020 • 🚀 1 minute read

react router logo

If you’re using React Router 5.1.0 or later and React 16.8.0 or later, you can now programmatically navigate with ease using the useHistory hook!

Let’s look at a quick example. Say you want to navigate somewhere on a button click. Previously, you might have had to pass the history object down your React component tree. With the new useHistory hook, you no longer need to do that!

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

function MyComponent() {
  const history = useHistory();

  function goToLogin() {
    history.push('/login');
  }

  return (
    <button type="button" onClick={goToLogin}>
      Login
    </button>
  );
}

And there you have it! We’ve retrieved our history object using a hook inside our function component. We can now use the push method on history to navigate the user somewhere!


Nick Scialli

Nick Scialli is a software engineer at the U.S. Digital Service.

Subscribe to the mailing list!

If you like what I post here, please sign up to get updates and code insights in your inbox. I won't spam you and you can unsubscribe any time!

Enter your email

Powered by Buttondown.

© 2020, Built using Gatsby

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK