Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use in Reactjs functional component history.push

I have a functional component that has form. Onsubmit call I would like to redirect to another page.

function ProfileForm(props) {
 // many code removed
 const onSubmit = (data, e) => {
   e.target.reset();
   history.push({
  pathname:  "/OnSubmit",
  state: {
    response: messageFromServer 
   } 
  }
}
// many code removed
}

I got this erro:-

Unexpected use of 'history' no-restricted-globals

After Googling the error I found a similar kind of answer for location. Answer was: Try adding window before location (i.e. window.location). So I tried:-

  window.history.push({
  pathname:  "/OnSubmit",
  state: {
    response: messageFromServer 
  } 
}

got new error:-

Unhandled Rejection (TypeError): window.history.push is not a function

like image 659
masiboo Avatar asked Mar 03 '20 22:03

masiboo


People also ask

How do you use history push in functional component react?

All we need to do is to call the useHistory hook inside a functional component: import { useHistory } from 'react-router-dom'; const App = () => { const history = useHistory(); const redirect = () => { history. push('/login'); } return ( <div> <h1>Hi there!

How do you use history PUSH IN react hooks?

“useHistory()” hook returns the history instance created by React Router, and history. push(“/profile/John”) adds the given URL to the history stack which results in redirecting the user to the given URL path. Similarly, you can use other methods and parameters of the history object as per your need.


Video Answer


3 Answers

I think you handle routing with react-router. If so, you need to use the history object which is passed through the ReactRouterContext. To do that, you need to use useHistory hook to get the history object.

// ...
import { useHistory } from "react-router";
// ...


function ProfileForm(props) {
  const history = useHistory();
  const onSubmit = (data, e) => {
     e.target.reset();
     history.push({
        pathname:  "/OnSubmit",
        state: {
          response: messageFromServer 
        } 
     });
  }
}
like image 127
Onur Önder Avatar answered Oct 16 '22 23:10

Onur Önder


Instead of history.push try to use navigate

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

const addToCartHandler = () => {
  navigate(`/cart/${productId}?qty=${qty}`)
};
like image 2
Anis Khoja Avatar answered Oct 16 '22 22:10

Anis Khoja


Use props.history Instead

const onSubmit = (data, e) => {
   e.target.reset();
   props.history.push("/OnSubmit")
  }
}
like image 1
May Avatar answered Oct 16 '22 23:10

May