I am using react-router with react js and i following their documentation but facing this error
while compiling it shows the error,
TypeError: _this.
you can use window.location.href = '/somePath'
as your last resort
For me the solution was to change
1) component as child
<Route path="/path">
<MyComponent/>
</Route>
to
2) component as the "component" prop
<Route path="/path" component={MyComponent}>
</Route>
In both ways it renders, so it was very confusing for me, in examples they provide code as in first example. (I used the version 5.1.2 of the "react-router-dom" package at the moment).
Update
You can also use this way (for child components (children of "MyComponent") works only this one)
import {withRouter} from 'react-router-dom';
const componentClassWithHistory = withRouter(ChildComponent);
export {componentClassWithHistory as ChildComponent};
or for default export
export default withRouter(ChildComponent)
or for typescript
const componentClassWithHistory = (withRouter(ChildComponent as any) as any);
export {componentClassWithHistory as ChildComponent};
Source: https://reacttraining.com/react-router/core/api/withRouter
Hope it helps someone.
Are you using npm? I had the same problem with "react-router": "^4.0.0" in my package.json. Changing it to "react-router": "^3.0.2" solved my problem.
The below solution works for me in ReactDOM.render:
<BrowserRouter>
<Switch>
<Route path="/home" component={Home} />
<Route path="/user" component={User} />
<Route path="*" component={page404} />
</Switch>
</BrowserRouter>
It use multiple Routing.
I encountered this problem when trying to instantiate my own Router rather than using one of the built-in ones, to deal with an issue of having access to the history:
history.js
import { createHashHistory as createHistory } from 'history'
export default createHistory()
root.jsx
import { Router, Route } from 'react-router-dom'
import history from './history'
...
<Router history={history}>
<Route path="/test" component={Test}/>
</Router>
In my case, the trouble was that I had a version of the history
package locked at v2.1.2, while react-router
was depending on a v4.x version of history
in its own dependencies. So the built-in routers instantiated fine using the newer history
, but when I tried to do it myself I was pulling in the older history
and getting an incompatible object.