Akshat Adsule
Akshat Adsule

Reputation: 63

Trying to redirect in react using react router

so I have a bug that I can't seem to solve. Currently I am using react with react router, however I cannot seem to get react to redirect to a page. Here is a expert from my code (keep in mind this is a functional component)

<Route path="/login">
  <Login
    onSubmit={(user) => {
      login(user, (status) => {
        if (status == 200) {
          history.push('/home');
        } else {
          history.push('/login');
        }
      });
    }}
  />
</Route>

(For reference, I have a login component which takes in a onSubmit callback and in which I call a predefined login method in check the status of the response from my backend and redirect accordingly)

When I run this code and redirect, I get a error that says

Unhandled Rejection (TypeError): Cannot read property 'push' of undefined

And just to be clear, I have defined history in the first few lines of my component

let history = useHistory();

Any help will be greatly appreciated!

Upvotes: 0

Views: 129

Answers (2)

Alex Mckay
Alex Mckay

Reputation: 3696

history is resolving to undefined so you are trying to invoke undefined.push('path'), hence the error. You need to make history accessible within the scope of the component like this:

import {useHistory} from 'react-router-dom'

const App = () => (
const history = useHistory()
return <Login onSubmit={() => history.push('/path')} />
)

Upvotes: 1

Ferin Patel
Ferin Patel

Reputation: 3968

You can use Redirect from react-router-dom

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

...

<Route path="/login">
  <Login
    onSubmit={(user) => {
      login(user, (status) => {
        if (status == 200) {
           return <Redirect to="/home" />
        } else {
          return <Redirect to="/login" />
        }
      });
    }}
  />
</Route>

Upvotes: 1

Related Questions