Daniil Galitskii
Daniil Galitskii

Reputation: 137

Cannot read property push of undefined for react use history

I wanna connect arrow up and down to change sections, and with it change url with useHistory but i get this error "Pages.jsx:15 Uncaught TypeError: Cannot read properties of undefined (reading 'push')" P.s. now i just wanna check if this will log and change URL

Code below

import {Route, Router, useHistory} from 'react-router-dom'
import Section1 from "./Pages/Section1";
import Section2  from "./Pages/Section2";
import '../css/Pages.css'


const Pages = () =>{
    const [count, setCount] = useState(0)
    const urls = ['/home', '/about', '/story']
    const history = useHistory()
    useEffect(() => {
        const keyCheck = (event) => {
            if(event.keyCode === 40){
                console.log('arrow down');
                setCount(count-1)
                history.push(urls[count])
                
            } else if (event.keyCode === 38){
                console.log('arrow up');
                setCount(count+1)
                history.push(urls[count])
            }
        }
        window.addEventListener('keydown', keyCheck);
        return () => {
            window.removeEventListener('keydown', keyCheck);
        };

    }, [count])

    return(
        <div id="fullPage">
            {/*<Router>
                <Route path='/report' component={Section2}/>

            </Router> */}
        </div>
    )
}

export default Pages

Upvotes: 0

Views: 485

Answers (1)

Thales Kenne
Thales Kenne

Reputation: 2932

You need to wrap the parent component in the Router. Or move the useHistory logic to a child component and place the child component inside the Router fragment.

Router provides the context for useHistory!

const Pages = () =>{
  return(
    <div id="fullPage">
        <Router>
            <RouterWithKeyNavigation />
        </Router> 
    </div>
  )
}

Then this file will be wrapped by the router component from react-router-dom

    const RouterWithKeyNavigation = () => {
       const [count, setCount] = useState(0)
        const urls = ['/home', '/about', '/story']
        const history = useHistory()
        useEffect(() => {
            const keyCheck = (event) => {
                if(event.keyCode === 40){
                    console.log('arrow down');
                    setCount(count-1)
                    history.push(urls[count])
                    
                } else if (event.keyCode === 38){
                    console.log('arrow up');
                    setCount(count+1)
                    history.push(urls[count])
                }
            }
            window.addEventListener('keydown', keyCheck);
            return () => {
                window.removeEventListener('keydown', keyCheck);
            };
    
        }, [count])
    
      return (<Route path='/report' component={Section2}/>)
    }

Upvotes: 1

Related Questions