0

I am a beginner in React and trying to learn things by myself. I have this code that I'd like to navigate to the Login page using useHistory but I can't seem to make it work. Hope you can help me. Here is my code below:

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

const App = () => {
    let history = useHistory();
    
    const MoveToLogin = () => {
        history.push('./container/Login');
    }

    return (
        <div>
            <button className='btn' text='User Login' onClick=. 
            {MoveToLogin}>Login</button>
        </div>
    );
}

export default App;
zhulien
  • 5,145
  • 3
  • 22
  • 36

3 Answers3

0
  1. First you need to add Provider 'Router' which is imported from 'react-router-dom'
  2. Define routes and corresponding components in routing file.
  3. You can only use history inside the children of Provider Router.
  4. Navigate to route using history.push('/login'). Don't provide relative path of component file here. Use the route you want to show in browser url
0

I have played around and did more research about useHistory. I was able to make it work. It has navigated to a new component. Please find my solution below. Hope it can help others with the same kind of issue.

import UserLogin from "./pages/UserLogin";

const ButtonLogin = () => {
  let history = useHistory();
  const MoveToLogin = () => {
    history.push('/pages/UserLogin');
  }
  return (
    <div><button className='btn btn-primary' onClick={MoveToLogin}>Login</button></div>
  );
}
const App = () => {
  return (
    <div>
      <Router>
        <Route path="/pages/UserLogin" exact component={UserLogin} />
        <Route path="/" exact component={ButtonLogin} />
      </Router>
    </div>
  );
}

export default App;

Refer to this answer as well for further information. Cannot read property 'push' of undefined for react use history

0

I hope you have the routes defined for the path specified

      <Router>
        <Route path="/container/Login" exact component={LoginComponent} />
      </Router>

The dot is not needed in your move to login function.

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

const App = () => {
    let history = useHistory();
    
    const MoveToLogin = () => {
        history.push('/container/Login'); // Here you don't need dot ./container
    }

    return (
        <div>
            <button className='btn' text='User Login' onClick=. 
            {MoveToLogin}>Login</button>
        </div>
    );
}

export default App;
dee
  • 2,244
  • 3
  • 13
  • 33