Skip to content Skip to sidebar Skip to footer

React Js: React Router Not Redirecting When Button Is Being Clicked

I have been trying to solve this problem for couple days and still couldnt get it to work. How does redirecting not work here? I keep getting the 'TypeError: history is undefined'.

Solution 1:

Simply because you are calling useHistory hook outside of React Router Switch Component, meaning you should use this hook in all Switch child components, otherwise the history object is undefined. The best way for my opinion is to move the button to the Home Component, then surly it will work.

I hope this answer helped you.

Solution 2:

If you use it like this

<Buttoncolor='primary'onClick={handleSub('/about')}>Submit</Button>

and in your method do it like this.

consthandleSub = (path) => async (e) => {
    history.push(path)}

I hope it will solve your issue.

Solution 3:

It's not the placement of the button which is the issue, but as originally mentioned, the placement of useHistory. The history hook is expecting context provided by the Router component - if you are familiar with useContext, it's exactly the same here. You must be calling useHistory inside a component which is a child of Router.

I'll mock an index.js file to demonstrate:

// index.jsimportReactfrom'react';
importReactDOM from'react-dom';
import { BrowserRouterasRouter } from'react-router-dom';
importAppfrom'./App';

const rootHtml = (
  <Router><App /></Router>
);


ReactDOM.render(rootHtml, document.getElementById('root'));

Remove the original router in the App component. Now this top level router has the App component in scope and can provide it with history context for useHistory to use.

Post a Comment for "React Js: React Router Not Redirecting When Button Is Being Clicked"