On a button click, I am getting the URL changed by doing history.push()
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
.
. some code
.
history.push(`/share/${objectId}`)
and hoping the component mentioned in the Route
for that URL would render but that is not happening. Though, on refreshing that component is getting rendered as expected. But I don't get that why it is not rendering as soon as the URL is changing. I've tried wrapping the component inside withRouter
.
import React, {Component} from 'react'
import {BrowserRouter, Router, Route, Switch, withRouter} from 'react-router-dom'
import createHistory from 'history/createBrowserHistory'
import Home from './pages/home'
import ViewFile from './pages/view-file'
const history = createHistory()
class App extends Component {
constructor(props) {
super(props)
}
render() {
return (
<BrowserRouter>
<Switch>
<Route exact path={'/'} component={Home}/>
<Route path={'/share/:id'} component={withRouter(ViewFile)}/>
</Switch>
</BrowserRouter>
)
}
}
export default App
as well as passing history in Router
which I think same as using BrowserRouter
.
import React, {Component} from 'react'
import {BrowserRouter, Router, Route, Switch, withRouter} from 'react-router-dom'
import createHistory from 'history/createBrowserHistory'
import Home from './pages/home'
import ViewFile from './pages/view-file'
const history = createHistory()
class App extends Component {
constructor(props) {
super(props)
}
render() {
return (
<Router history={history}>
<Switch>
<Route exact path={'/'} component={Home}/>
<Route path={'/share/:id'} component={ViewFile}/>
</Switch>
</Router>
)
}
}
export default App
but not getting any luck with this. Can anyone explain why is this happening?
P.S I went through the answers here but they didn't help
One of the symptoms of this incompatibility is history. push() calls not triggering a re-render.
What is the purpose of push() and replace() methods of history ? A history instance has two methods for navigation purpose. If you think of the history as an array of visited locations, push() will add a new location to the array and replace() will replace the current location in the array with the new one.
Note: You can only use this. props. history. push() function inside the component page that already listed on your project route, or simply use the withRouter() HOC if the component is not available in the route list.
This may help someone. Make sure the history
package version are compatible with the react-router-dom
.
This combination didn't work for me:
history: 5.0.0
with react-router-dom: 5.2.0
This combo did:
history: 4.10.1
with react-router-dom 5.2.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With