Home > database >  React Link to current URL does not reload page
React Link to current URL does not reload page

Time:03-18

I have an image logo on my ReactJS website which has a link to load the current page URL. I can see that the URL is correct (when I hover on the image, the correct URL is displayed at the bottom left corner of the browser), but when I click on the image the page does not reload.

<Link to={`${window.location.pathname}`}>
     <img className="img-fluid" src={Logo} alt="Alt_Text />
</Link>

Is there any way to reload the page without using an onClick handler in the Link?

CodePudding user response:

If you want to force the window to reload, you can try to use window.location.reload() in any event you wanna trigger.

React-Router-Dom will only redirect your url history only if it detects any change, and it will not reload page at all because React is typically used to build Single-Page-Application (SPA). Therefore, what you are asking is contradicting to the principle of React and React-Router-Dom.

CodePudding user response:

If you really must know...
You can get it to reload by changing your code just slightly

<Link to={`${window.location}`}>
    <img className="img-fluid" src={Logo} alt="Alt_Text" />
</Link>

This works because window.location has the entire URL (not just the current relative path), since it is an entire location it will force the reload... Not sure why you don't just use an onClick, but this is the correct way to force the reload given your criteria.

  • Related