0

In my react app, I am using the useHistory hook to redirect to my Home Component. Why is useHistory undefined, and how would I solve this problem?

App.js

import 'bootstrap/dist/css/bootstrap.css' 
import React from "react";
import { Button } from 'react-bootstrap';
import { BrowserRouter, Route, useHistory} from 'react-router-dom';

import { Switch } from 'react-router-dom/cjs/react-router-dom.min';
import './App.css';
import Home from './components/Home/Home';



const App = () =>
{
  const history = useHistory()
  const handleClick = () => 
  {
    console.log(history)
    console.log("handle click")
    // history.push("/home") this line throws "cannot read property of undefined" error
  }

    return (
      <>
        <BrowserRouter>
          <Button onClick = {handleClick} variant = "primary">Get Started</Button>
  
          <Switch>
            <Route path="/home" exact component = {Home}/>
          </Switch>
        </BrowserRouter>
  
      </>
    );      
}

export default App;
Alan
  • 79
  • 1
  • 7
  • could you check if this helps https://stackoverflow.com/questions/58220995/cannot-read-property-history-of-undefined-usehistory-hook-of-react-router-5 – albert Dec 13 '20 at 22:48

1 Answers1

0

Try to use the useHistory() outside this component and see it work. It seems you are calling the function before the Router itself and both are imported from react-router-dom .

taiwo sunday
  • 25
  • 1
  • 8