Dokucan
Dokucan

Reputation: 48

useHistory - Cannot read property 'push' of undefined

When the home button is pressed I want to redirect it to the home page '/ '. But I am getting this error. What can I do ? :

import { Route, useHistory } from 'react-router-dom/cjs/react-router-dom.min';
const history = useHistory();

const homeButtonOnClickHandler = () =>{
    history.push("/");
}
  
<Router>
    <Header homeButtonOnClickHandler={homeButtonOnClickHandler}/>
    <Switch>
        <Route path='/result'>
            <Result
                ingredients={ingredients}
                total={() => hesapla()} 
            />
        </Route>

        <Route path='/'>
            <Home
                ingredients={ingredients} 
                total={() => calculate()} 
                ingredientAdd={(i) => ingredientAdd(i)}
                ingredientRemove={(i) => ingredientRemove(i)}
                selectedIngredients={ingredients}
                isOrder={number}
            />
        </Route>
    </Switch>
</Router>

Upvotes: 2

Views: 696

Answers (2)

Furkan Sahin
Furkan Sahin

Reputation: 48

You are trying to use history hook outside of Router. Write your function inside Header component.

Try this inside Header component

const history = useHistory();

const homeButtonOnClickHandler = () =>{
            history.push('/');
}

Upvotes: 1

Mike Kokadii
Mike Kokadii

Reputation: 513

You just need to put hook and handler into component like here: link

Upvotes: 1

Related Questions