RuLee
RuLee

Reputation: 193

"Uncaught TypeError: history.push is not a function" error occurs

I have been developing a navigation bar. I wrote a function to switch screens and call it in button onClick. I wrapped the component in withRouter also. But the following error occurs:

Uncaught TypeError: history.push is not a function" error.

This is my code:

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

function Navigation(history) {
  const abc = path => {
    history.push(path);
  };

return(
<button onClick={() => abc('/user')}>User</button>
);}

export default withRouter(Navigation);

Thank you

Upvotes: 12

Views: 41635

Answers (5)

fanjieqi
fanjieqi

Reputation: 572

For umi users, we should add this:

import { history } from 'umi';

Upvotes: 0

gdibble
gdibble

Reputation: 1446

Per react-router-dom v5 → v6 migration

The old useHistory has been replaced by useNavigate

@see https://reactrouter.com/docs/en/v6/api#usenavigate

Old v5 code:

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

const history = useHistory();
history.push(`/Search?${queryString}`);

New v6 code:

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

const navigate = useNavigate();
navigate(`/Search?${queryString}`);

Upvotes: 16

Raiden Choong
Raiden Choong

Reputation: 63

Try this it works for me.
Using history(path) instead of history.push(path)

function NavItem1(props) { //Navigate to the home page
  const history = useNavigate();

  const redirect = path => {
    history(path);
  };

  return (  
    <a href="#"  className="icon-button" onClick={() => redirect('/')} >
    {props.icon}
  </a>

  )
}

Upvotes: 3

user0101
user0101

Reputation: 1527

You have to destruct all the props like Navigation({ history })

Upvotes: 2

wentjun
wentjun

Reputation: 42576

You have wrapped the Navigation component with withRouter, thus you will need to access the history object via the component's props. You may choose to destructure your props as shown below:

function Navigation({ history }) {
  const abc = path => {
    history.push(path);
  };

  return (
    <button onClick={() => abc('/user')}>User</button>
  );
}

export default withRouter(Navigation);

Since you are working with functional components, an alternative way of doing things would be to make use of the useHistory hook, which spares you the need to wrap your component with withRouter:

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

function Navigation(props) {
  const history = useHistory();

  const abc = path => {
    history.push(path);
  };

  return (
    <button onClick={() => abc('/user')}>User</button>
  );
}

export default Navigation;

Upvotes: 8

Related Questions