I just took a look at the latest documentation and I think I understand what is going on with an empty string for the to
prop of a Link component. Since that is the question here, I will try to explain.
According to the docs, if the to
value doesn't start with a slash (/
) then it is considered a relative link and the following is the expected behavior:
A relative value (that does not begin with /) resolves relative to the parent route, which means that it builds upon the URL path that was matched by the route that rendered that .
Unfortunately this doesn't mean that an empty string will just link to the URL you are already on. If you had a route like this:
<Route path="/questions/:id" element={<MyElement />} />
and a URL like:
https://stackoverflow.com/questions/57586239/is-empty-string-valid-value-for-react-link
the 'match' part is just https://stackoverflow.com/questions/57586239
, and this is what the Link with empty to
will link you to. In fact you will see it as the href of the <a>
element.
Even if your matched route exactly equals the current URL, so it seems like empty string trick might work, each Link click will create an entry in the navigation history which will mess up navigating backwards and forwards if the intention is for the link to be a no-op.
This last point means that even using a trick like <Link to={window.location.href}>
won't work because it will still pollute the navigation history.
There are plenty of good alternative suggestions as answers to this question that will work, but I wanted to try to answer why empty string as to
is a bad idea.