1

In HTML I can use <a href="#"></a> or <a href="javascript:void(0)"></a> to create a link that doesn't lead anywhere. How do I do the same thing with react-router Link's to property? It's not allowed to pass undefined or null, only a string or an object. Passing # doesn't work, passing empty string results in the same behavior as if I passed /. I need to do it conditionally, so sometimes Link will have a real pathname and sometimes it should be empty, so I cannot use normal a element. The work-arounds I thought of were to render a instead of Link conditionally or pass a function like

(location: Location) => ({ ...location, href: '#' })

to the to property, but is there a more elegant way?

Alex Chashin
  • 3,129
  • 1
  • 13
  • 35
  • Does this answer your question? [Is empty string valid value for React Link?](https://stackoverflow.com/questions/57586239/is-empty-string-valid-value-for-react-link) – vivalldi Dec 14 '20 at 15:02
  • @vivalldi, no, I wrote that empty string is treated as `/` in the `Link` component, so it redirects user to the main page of my app and I just want it to do nothing – Alex Chashin Dec 14 '20 at 15:10
  • Correct, and option 2 in the top answer shows how you could conditionally set the link – vivalldi Dec 14 '20 at 15:13
  • @vivalldi, but if I set `to` property to an empty string or a space, pressing the link redirects user to main page of my application, the `/` route. I don't want this, I want the link to do nothing. Like I have a page `/profile` I want to press the link and stay at `/profile` and using space as `to` attribute will change route to `/` – Alex Chashin Dec 14 '20 at 15:15
  • In that case, just use option 3. You add a `onClick` handler that checks the condition. If condition, then prevent default to prevent navigation (might be some issues with the `preventDefault` but I would have to dive into react router docs to find out the specifics – vivalldi Dec 14 '20 at 15:26
  • @AlexChashin Add a css class to the link when there is no url that has `pointer-events: none !important` – rnmalone Dec 14 '20 at 15:30

0 Answers0