Short version: When the user clicks a button, I want to do something, then reroute the user. How do I do this?
Longer version:
I have nested routes (don't know if this has any effect to the problem at hand) how this is setup is described in a pretty minimal (to the best of my knowledge) example here: link to SO question
I want a button, that first does something, then reroutes the user, therefore I can't use Link
. First all I saw was
use
this.props.history.push('/route')
for that
But then I learned that this.props.history
isn't a thing anymore and is now it's own npm package. Here I got a simple explenation on how to implement what I needed.
Example of my problem:
App.js
render this:
<Router history={history}>
<div>
<Link to="/">
<button>Go to home</button>
</Link>
<Switch>
<Route exact path="/other" component={() => <Other/>} />
<Route path="/" component={() => <Home/>} />
</Switch>
</div>
</Router>
With two top level routes, an exact path for /other
that render Other
and looks like this:
and a relative path for /
that render Home
and looks like this:
Home
renders this code:
<div>
THIS IS HOME WOO!
<div>
<Route exact path="/" component={() => <HomeController/>} />
<Route exact path="/about" component={() => <About/>} />
<Route exact path="/click-page" component={() => <ClickPage/>} />
</div>
</div>
Now here the default is HomeController
(containing two buttons with links to about and click-page), but /about
renders About
and looks like this:
and /click-page
renders ClickPage
and looks like this:
This is where the problem starts :(
So ClickPage
renders this:
<button onClick={clickHandler}>
DO SOMETHING THEN GO TO ABOUT
</button>
where clickHandler
looks like this:
function clickHandler(){
console.log("doing stuff");
history.push('/about');
}
history
in this case is imported from another file that looks like this:
// history.js
import { createBrowserHistory } from 'history'
export default createBrowserHistory({
/* pass a configuration object here if needed */
})
which is character by character copied from the answer i mentioned earlier.
Problem is, when I click the button, this is what I see:
So the function is called, it does something, and then it pushes "/about" to history, but nothing happens. Why is this? Do I need to force Home
to rerender?
The full example code I've used to recreate the issue is here: pastebin-link