TypeError: Object(...) is not a function when using useHistory() hooks

Viewed 7394

i have an onClick event on a button that pushes requests to a server and should go back to the homepage afetr submitting , i tried to use the Reactjs useHistory hooks on that component ,however i keep getting the error TypeError: Object(...) is not a function.

I need help to get around it

4 Answers

Are you using react-router: 5.1.0? useHistory and other hooks didn't become available until then. I was getting the same error as OP using the simplest implementation and then realized I was only on react-router: 5.0.0

I was getting error -

TypeError: Object(...) is not a function

Solution - Looks like usehistory was deprecated for react-router-dom v6 and up. Instead try using useNavigate

Example -

import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate('/home')

Docs - You can view the official docs here from react-router

You can see this error

TypeError: Object(…) is not a function

when using useHistory() hooks in React class. You are not supposed to do it. Instead you are better to use the withRouter high-order component for class or context API, see link.The basic example is like this:

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

class MyClass extends React.Component {
  ...

  handleEvents = (e) => this.props.history.push('another-route')

  render(){
    return <div onClick={e => handleEvents(e)}>Hello World!</div>
  }
}

const MyClassWithRouter = withRouter(MyClass)
export MyClassWithRouter 
Related