How to properly use useHistory () from react-router-dom?
Asked Answered
A

8

43

How to use useHistory() correctly? I can't make the transition from one react component to another. According to the instructions from the React documentation and also here on Stack Overflow, I cannot make the transition from App.js to MyComponent.js.

For example - I am trying

/* **App.js ** */
/* Import modules */
import React from 'react';
import { useHistory } from 'react-router-dom'; // version 5.2.0

function App()
{
    let history = useHistory ();
    const handleClick = () => {
       history.push ('./pages/MyComponent');
    }    

    return (
       <div className="App">
          <button onClick={handleClick}>Next page ==></button>
       </div>
    );
}

I also tested this example, but the output throws the following error when the button is pressed:

TypeError: Cannot read property 'push' of undefined

Does something seem to be leaking to me or is there a mistake on Babel's side?

Project react structure:

+ Root/
    + src/
        - App.js
        - index.js
        + pages/
            - MyComponent.js
    
Apparition answered 14/11, 2020 at 21:3 Comment(2)
Could it be that you have a space between push and the parentheses?Galenism
There is no mistake. (I tried it). @GalenismTurnbow
C
25

You can't just use the useHistory hook to redirect to another page. You need to properly set up your application in order to use React Router. Look at their examples starting from this https://reactrouter.com/web/example/basic

You need to wrap your entire application with <BrowserRouter /> which will give the history object you are looking for through the hook.

By the way, you don't give a relative file path to history.push as an argument, you must give a valid route that you typically setup using <Route /> component

Conceptacle answered 14/11, 2020 at 21:59 Comment(0)
S
111

This has changed in v6, useHistory is now useNavigate and we can use it as follows:

instead of:

const history = useHistory()
history.push('/')

we now use:

const navigate = useNavigate()
navigate('/')
Stalagmite answered 8/12, 2021 at 12:22 Comment(4)
can i navigate i step back , like prev page using useHistory ?Disenable
useHistory() is dead now, don't use itStalagmite
@Stalagmite I am using ^5.3.0 react-router-dom still face same issueTony
@HowtoProgram Pass the delta you want to go in the history stack. For example, navigate(-1) is equivalent to hitting the back button.Centeno
C
25

You can't just use the useHistory hook to redirect to another page. You need to properly set up your application in order to use React Router. Look at their examples starting from this https://reactrouter.com/web/example/basic

You need to wrap your entire application with <BrowserRouter /> which will give the history object you are looking for through the hook.

By the way, you don't give a relative file path to history.push as an argument, you must give a valid route that you typically setup using <Route /> component

Conceptacle answered 14/11, 2020 at 21:59 Comment(0)
B
5

Using React 17.0>, this works for me:

import { useHistory } from "react-router-dom";

const history = useHistory();
history.push("/home");

I've reached too much to find this correctly use of the useHistory function. Try and answer this post for feedback.

Belga answered 20/5, 2022 at 18:10 Comment(0)
E
5

useHistory is replaced by useNavigate in react-router-dom v6

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

For reference,

import './App.css'
import About from './Components/About'
import Profile from './Components/Profile'
import { Routes, Route,useNavigate } from 'react-router-dom'

function App() {
  const navigate=useNavigate()
  return (
    <div>
       <button onClick={()=>navigate('/about')}>about me</button>
       <button onClick={()=>navigate('/profile')}>profile</button>
        <Routes>
          <Route element={<About/>} path='/about' />
          <Route element={<Profile/>} path='/profile' />
        </Routes>
    </div>
  )
}
export default App
Essex answered 13/12, 2023 at 6:3 Comment(0)
R
1

you need to use it with react-router-dom. set your router config and then push it to that path. you can get more information by looking at documentation.

https://reactrouter.com/web/example/route-config

do not forget to set your switch components and your exact for root path.

Redware answered 14/11, 2020 at 21:40 Comment(4)
we can't see his routes. app.js usually contain that Routes and there is a route that sends you to the first component. it seems he is trying to get history from the first component without set any routes.Corrinecorrinne
i agree. he is using relative path not absolute.Redware
ya he can use the withRouter but there is no sue if you build stuff the right wayCorrinecorrinne
I updated the question and added the tree structure of the project. @CorrinecorrinneTurnbow
G
1

Using history.replace('/<route-name>') also works.

Granese answered 12/2, 2021 at 19:17 Comment(1)
I'm downvoting this because the problem is that he doesn't have history in scope in the first place, not that the push method isn't working and was looking for an alternative method. In his case, neither push nor replace would work.Fefeal
S
1

When you are applying history.push, is that your path name? history.push('/pathname') is the process I guess. You can see here: https://reactrouter.com/web/api/Hooks

Stratus answered 8/9, 2021 at 17:41 Comment(0)
B
1

it's not supported anymore in 'react-router-dom', i try this and it's working good :

const goBack = () => {
    window.history.back();
  };
Boole answered 13/3 at 11:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.