'React Link doesn't refresh the page
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?
Solution 1:[1]
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.
Solution 2:[2]
If you use this, it will go to the link and also reload
<a onClick={() => {window.location.href="/something"}}>Something</a>
Solution 3:[3]
I will use react-router-dom version 6 for this example:
- Before starting make sure you have the correct version#
$ 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) :
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Ferdousi |
Solution 3 |