this.props.history.push() no longer seems to work in React Router v4, what's the alternative?

Viewed 5529

I'm new to React, and most of the tutorials I see about redirecting using React Router seem to be using the aforementioned snippet. What I am trying to achieve is to redirect the user to the home page of my website upon successful login. I have tried history.push but according to my google searches, it doesn't work in Router v4 anymore. What can I do as an alternative? I'm open to both stateful and stateless solutions.

To clarify, here's the workflow -

  1. User fills in a textbox with their username
  2. User fills in a textbox with their password
  3. User hits the submit button
  4. An API gets called with the username and password to authenticate the user
  5. The API returns success for successful login
  6. Upon successful login, the user is redirected to the home page
4 Answers

history.push('./path') is still usable in React Router v4 you need to add withRouter

example

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import compose from 'recompose/compose'

class Test extends Component {
  render () {
    const { history } = this.props

    return (
     <div>
       <Button onClick={() => history.push('./path')}
     </div>
    )
  }
}

export default compose(
  withRouter,
)(Test)


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

export default function navigationExample() {
  const navigate = useNavigate();
    
  return (
    <>
       <Button
          type="ice"
          text="WHITELIST"
          onCLick={() => navigate("/login")}
        />
    </>
  );
}

history.push(location) still can be used

https://reacttraining.com/react-router/core/api/history/history-is-mutable

// usually all you need
<Link to="/somewhere"/>

// but you can use a location instead
const location = {
  pathname: '/somewhere',
  state: { fromDashboard: true }
}

<Link to={location}/>
<Redirect to={location}/>
history.push(location)
history.replace(location)
Related