I have this code:
<Link to="/dashboard" style={{ color: '#A4A4A4' }}>Dashboard</Link>
As part of my app, but if i'm currently viewing the /dashboard route, the page doesn't refresh.
Why? And how can i make it refresh?
You can try forcing a refresh, either with:
<Link to="/dashboard" onClick={this.forceUpdate} style={{ color: '#A4A4A4'}}>Dashboard</Link>
or
<Link to="/dashboard" onClick={() => window.location.reload()} style={{ color: '#A4A4A4' }}>Dashboard</Link>
You can also add logic to the onClick method to check which page you are currently on, and to only refresh if you are on the dashboard.
react-router-dom will not refresh the page for you if you are navigating to the current page.window.location.reload()?It doesn't refresh when you go to the same page.
You can use <Link reloadDocument> to skip client side routing and let the browser handle the transition normally (as if it were an <a href>).
<Link reloadDocument to="/dashboard" style={{ color: '#A4A4A4' }}>Dashboard</Link>
Conceptually, if your browser bar is already on "/dashboard" and you try to navigate to that, then you shouldn't expect any update. If you do know that things have changed underneath then you need to tell React what parts of the page have changed. You do this by:
The other answers suggest you do a full page refresh but this is not good style...it's using a sledgehammer to solve your problem and comes with its own problems, such as you losing state and doing more re-rendering than needed.
I will use react-router-dom version 6 for this example:
$ yarn add react-router-dom@6 or $ npm install react-router-dom@6
What is important to note is that I have my link tag inside the router tag. I believe this is is important to have in order to navigates to the respective route path. You can do this by having a navigation component like so (for more context I added my folder structure) :