Categories
JavaScript Answers

How to fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom?

Spread the love

Sometimes, we want to fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom.

In this article, we’ll look at how to fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom.

How to fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom?

To fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom, we call the useHistory hook.

For instance, we write

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

to import the useHistory hook.

Then we write

const history = useHistory();

to get the history object from the hook.

Then we use

history.push("/foo");

in a component function to navigate to /foo.

Conclusion

To fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom, we call the useHistory hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *