Reputation: 411
Why do I get this error?
Invariant Violation: You should not use withRouter() outside a <Router>
... and how do I fix it?
I think I am misuing withRouter somehow
import React, {Component} from "react"
import axios from "axios"
import { withRouter } from 'react-router-dom'
class LoginForm extends Component {
constructor(props) {
super(props)
}
handleSubmit = (event) => {
this.props.history.push("/dashboard")
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="submit" />
</form>
)
}
}
export default withRouter( LoginForm )
index.js is just:
ReactDOM.render(
<LoginForm />,
document.getElementById("root")
)
Upvotes: 0
Views: 931
Reputation: 4199
withRouter
is a higher order component that will pass closest route's match
, current location
, and history
props to the wrapped component whenever it renders. simply it connects component to the router. source
So your problem is that withRouter
isn't able to connect to the closest router since there are none. You can fix it by adding one:
ReactDOM.render(
<BrowserRouter>
<LoginForm />
</BrowserRouter>,
document.getElementById("root")
)
Upvotes: 1