Debadeep Sen
Debadeep Sen

Reputation: 465

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

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

Upvotes: 5

Views: 8638

Answers (4)

Mayuresh bandekar
Mayuresh bandekar

Reputation: 1

you can use useNavigate function to navigate to the other page by simply using useNavigate from react-router-dom and navigate to the page you want first import it from react-router-dom library

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

export default function login() {
  const navigate = useNavigate();
     
  const handleSubmit = () => {
     navigate("/routeName_that_you_wish_to_navigate_to");
  }
  return (
    <>
      <Button
          type="submit"
          text="Submit"
          onCLick={() => handleSubmit()}
        />
    </>
  );
}

Upvotes: 0

Ali Raza
Ali Raza

Reputation: 1073

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

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

Upvotes: 1

Antoni
Antoni

Reputation: 1443

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)


Upvotes: 1

Johnny Zabala
Johnny Zabala

Reputation: 2483

You can use the Redirect component. https://reacttraining.com/react-router/web/api/Redirect

Upvotes: 0

Related Questions