

Programmatically Navigate Using React Router and Hooks
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
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 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 emailRecommend
-
10
Tutorial Angular Router: Navigation Using RouterLink, Navigate, or NavigateByUrl Angular ...
-
6
-
9
React router用hooks读取routeName、根据routeName跳转如果您发现本文排版有问题,可以先...
-
6
Single-page apps (SPAs) allow multiple views on the same web page, and Angular Router helps you navigate those and decide what to do about the URL for each view.Building single-page applications (SPAs) is fun, especially when you're getting s...
-
6
BackReact Router Hooks: Exploring How They WorkApril 13th, 2021 · 5 min read
-
14
Build an Exercise Tracker App using React.js (Hooks) and React Router | Learn React.js Jun 8 ・1 min read...
-
3
How to Programmatically Navigate with React RouterWith react-router I can use the Link element to create links which are natively handled by react router.I see internally it calls thi...
-
6
Remotion is a suite of libraries building a foundation for creating videos programmatically using React. Why create videos in React? Leverage web technologies: Use all of CSS, Canvas, SV...
-
3
How to Use 3 Popular React Hooks with React Router
-
8
Programmatically Search and Highlight Text in PDFs using C# in .NET Quick Start...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK