how to use in Reactjs functional component history.push

Viewed 34349

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

4 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 
        } 
     });
  }
}

Instead of history.push try to use navigate

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

const addToCartHandler = () => {
  navigate(`/cart/${productId}?qty=${qty}`)
};

If you are using import { withRouter } from "react-router-dom"; In your functional component, aren't you missing props.history.push?

You can use useHistory(). The follwoing code can help you.

import { useHistory } from "react-router";

export default function Checkout(props) {
    
const history = useHistory();
 
return (
              <React.Fragment>
                <AddressForm history ={ history} ></AddressForm>
              </React.Fragment>
        </Paper>
      </main>
    </React.Fragment>
  );
}
Related