React Route Changes not Re-rendering Some Components
I wanted to have part of my rendered page update whenever the route changes.
I'm continuing my journey into React and I wanted to have part of my rendered page update whenever the route changes.
I am generally doing this during a login/logout and the content for logging in and logging out needs to update. I also want my components to be rendered only for certain routes using the Switch
element/component or whatever React calls it.
My initial code for my routes.tsx
file was:
<Router history={history}>
<div>
<App history={history}></Route>
<Switch>
<Route path="/" exact render={(props) => <Home {...props} />}></Route>
<Route path="/home" render={(props) => <Home {...props} />}></Route>
<Route component={NotFound} />
</Switch>
</div>
</Router >
The problem was that the App
component was not being refreshed when the route changed. The solution that I found was to wrap the App
component inside of an empty Route
. I changed the App
line to be the following:
<Route render={(props) => <App history={history} {...props} />}></Route>
This fixed it, my App
component now refreshes as expected when the route changes.