Reputation: 157
I have to use this.props.history.push('/...') in a nested component so I added withRouter() to navigate without history problems using react-router-dom.
But since I have added withRouter, I have You should not use Route outside a Router error. I have read posts about this error but I can't understand what is wrong with my code.
Root.js:
import { BrowserRouter as Router, Route, Switch, Redirect, withRouter} from 'react-router-dom'
...
const Root = ({ store }) => (
<Router>
<Provider store={store}>
<StripeProvider apiKey="pk_test_XXXXXXXXX">
<Switch>
<Route exact path="/" component={App} />
<Route path="/comp1" component={Comp1} />
<Route path="/comp2" component={Comp2} />
<Route path="/store" component={MyStoreCheckout} />
<Route component={Notfound} />
</Switch>
</StripeProvider>
</Provider>
</Router>
)
Root.propTypes = {
store: PropTypes.object.isRequired
}
export default withRouter(Root)
and index.js:
import { createStore } from 'redux'
import myReducer from './redux/Reducers/myReducer'
import Root from './Root'
import Store from './redux/Store/store'
render(<Root store={Store} />, document.getElementById('root'))
I use withRouter to be able to call this.props.history(...) in CheckoutForm MyStoreCheckout.js:
class MyStoreCheckout extends React.Component {
render() {
return (
<Elements>
<InjectedCheckoutForm />
</Elements>
);
}
}
export default MyStoreCheckout;
CheckoutForm.js:
class CheckoutForm extends React.Component {
handleSubmit = () => {
fetch(getRequest)
.then((response) => response.json())
.then(...)
.then(() => this.goToSuccessPage())
}
goToSuccessPage(){
this.props.history.push('/') ; //----- error is here if I have no withRouter
render() {
return (
<form onSubmit={this.handleSubmit}>
<DetailsSection/>
<CardSection />
<button>Confirm order</button>
</form>
);
}
}
export default injectStripe(CheckoutForm);
Upvotes: 1
Views: 990
Reputation: 6805
As I mentioned in my comment... Just import withRouter
at the top of your CheckoutForm
file, then wrap the export with it, at the bottom. Like this:
CheckoutForm.js:
import { withRouter} from 'react-router-dom'
class CheckoutForm extends React.Component {
// ... your class code ...
}
export default withRouter(injectStripe(CheckoutForm));
If your injectStripe
HOC doesn't pass all of the props from withRouter
down to CheckoutForm
, you can try doing export default injectStripe(withRouter(CheckoutForm));
instead, but order shouldn't matter (if set up correctly)
Upvotes: 1