Reputation: 41
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:
Index.js (starting point):
<BrowserRouter>
<App />
</BrowserRouter>
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!
Upvotes: 1
Views: 2619
Reputation: 203099
Route props are not being passed to App
component, so history
is undefined.
<BrowserRouter>
<App />
</BrowserRouter>
Wrap App
component with the withRouter Higher Order Component to have the route props injected.
import { ..., withRouter, ... } from 'react-router-dom';
...
export default withRouter(App);
Now this.props.history
will be defined and usable.
handleCheckout( status) {
if (status === "success") {
this.props.history.push("/pymt/success");
}
}
Convert App
to a functional component and use the useHistory React hook from react-router-dom
.
App
import { ..., useHistory, ... } from 'react-router-dom';
...
const history = useHistory();
...
handleCheckout( status) {
if (status === "success") {
history.push("/pymt/success");
}
}
Upvotes: 0
Reputation: 41
History is not being passed to App.js. I have solved it by using {withRouter} from 'react-router-dom':
App.js:
import {withRouter} from 'react-router-dom'
class App extends Component{
...
handleCheckout(status){
const {history} = this.props;
if (status){
history.push("/pymt/success");
}
}
....
}
export default withRouter(App);
Thank you for pointing me in the right direction!
Upvotes: 1