Trying to redirect in react using react router

126 views Asked by At

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!

2

There are 2 answers

1
Alex Mckay On BEST ANSWER

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')} />
)
4
Ferin Patel On

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>