Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
'TypeError: Cannot read properties of undefined (reading 'push')' when using 'useHistory' hook of 'react-router-dom'

I'm trying to use the "useHistory" hook from 'react-router-dom' and I come across the error, 'TypeError: Cannot read properties of undefined (reading 'push')'. Below is my code.

import './App.css';
import { React, useState } from 'react'
import Header from './Header';
import Register from './Register';
import Login from './Login';
import { BrowserRouter as Router, Switch, Route, useHistory } from 'react-router-dom'

function App() {
  const [ loggedIn, setLoggedIn ] = useState(false)
  const history = useHistory()

  return (
    <Router>
      <Header />
      <Switch>
        <Route exact path='/'>
          {loggedIn ? <h1>Logged In</h1> : <Register setLoggedIn={setLoggedIn} />}
        </Route>
        <Route path='/log-in'>
          {loggedIn ? () => history.push('/') : <Login setLoggedIn={setLoggedIn} loggedIn={loggedIn} />}
        </Route>
      </Switch>
    </Router>
  );
}

export default App;

Why is 'history.push' causing this error within my ternary operator?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

import { React, useState } from 'react'
import { BrowserRouter as Router, Switch, Route, useHistory } from 'react-router-dom'
import Login from './login';

function App() {
  return (
    <Router>
      <Switch>
        <Route path='/log-in'>
         <Login/>
        </Route>
      </Switch>
    </Router>
  );
}

export default App;

import { useEffect, useState } from "react"
import { useHistory } from "react-router-dom"

const Login=()=>{
  const history=useHistory()
  const [loggedin,setloggedin]=useState(true)
  useEffect(()=>{
    if(!loggedin){
      history.push("/")
    }
  },[loggedin])
  return(
    <div>login</div>
  )
}
export default Login

In your code, the code inside your route only will be executed that is

{loggedIn ? () => history.push('/') : <Login setLoggedIn={setLoggedIn} loggedIn={loggedIn} />}

In which the code inside your app component will not be executed. You can try the above code.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!