How to redirect to another page after Stripe React successful response?

I have a very simple React app that uses Stripe to process payments. Payment processing works and I am receiving successful response. However, I cannot figure out how to redirect to another page. I am using react-router-dom.
Here is what I have:

App.js (Route definition to Payment.js and onSuccessfulResponse handler):

handleCheckout( status) {
    // HOWTO: redirect to success page?
    if (status === "success") {
       // history.push("/pymt/success");   // fails with  Unexpected use of 'history'
    }
}

render() {
    return (
        <div>
            <Switch>
                <Route path="/pymt/success">
                    <PymtSuccess />
                </Route>
                <Route path="/pymt">
                    <Payment onSuccessfulResponse={(status) => this.handleCheckout( status) } />
                </Route>

Payment.js contains only UI elements to display Stripe payment form:

                <Elements stripe={stripePromise}>
                    <CheckoutForm onSuccessfulResponse={( status) => this.props.onSuccessfulResponse( status) } />
                </Elements>

CheckoutForm.js processes payment. I am triggering onSuccessfulResponse with this code:

if (succeeded) {
    //return <div>Charge suceeded!</div>
    onSuccessfulResponse("success");
}

It goes to App.js -> handleCheckout function. But I cannot get it to go to another page.

I’ve been trying to solve this for the whole day with no luck. Greatly appreciate your effort in helping solve this!

Thank you!

1 thought on “How to redirect to another page after Stripe React successful response?”

  1. if you use react-router-dom, get history from props

    class Comp extends React.Component {
    
      handleCheckout(status) {
        // HOWTO: redirect to success page?
        if (status === "success") {
           this.props.history.push("/pymt/success");
        }
      }
    
      render() {
        return (
            <div>
                <Switch>
                    <Route path="/pymt/success">
                        <PymtSuccess />
                    </Route>
                    <Route path="/pymt">
                        <Payment onSuccessfulResponse={(status) => this.handleCheckout( status) } />
                    </Route>
               </Switch>
      }
    }
    

    history

    Reply

Leave a Comment