react: React@16.9 block `javascript:void(0);`

<a href="javascript:void(0);"></a>

Warning: A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed “javascript:void(0);”.

react@16.9

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 15 (2 by maintainers)

Commits related to this issue

Most upvoted comments

You could use <button type="button" onClick={}>...</button>, the added benefit here is that the role of the element is better communicated to screen reader users using your feature 👍

We encountered this issue too. The following didn’t work for us as it would refresh the page:

<a href="#" onClick={e => e.preventDefault()}></a>
<a href="#! onClick={e => e.preventDefault()}</a>

What did work was using the NavLink inside the react-router-dom library. We were already using it and it perfectly mimics the javascript:void(0) behaviour (but without the warning!).

<NavLink to="#" onClick={e => e.preventDefault()}>

@aweary If the ability to use javascript:void(0) is being removed then React should ship an alternative way to create links that act like buttons. A brief glance at StackOverflow shows that there is no reasonable alternative to javascript:void(0). What about just whitelisting this specific string? That would solve this usability problem while not introducing any security concerns.

href attribute without value and equal sign works

<a href></a>

To make sure its cross browser compatible use unused ID.

<a href="#nolink"></a>

Don’t add id="nolink" to any tag in HTML page.

@aweary I agree with raxod502 I have a specific problem where I am using an API for authentication. If I change the element from a anchor to a button the API no longer works because the js that is not exposed to me is still looking for an a tag. I will be forced to put inline js for prevent default and change the href to a hash tag which I do not think is a good solution.

@aweary is there a React recommended way to get the previous behavior of href="javascript:void(0);"? Not having an href gets rid of the default keyboard behavior tab and tab -> enter to behave like onClick. Using # gets that behavior but the onClick handler then has the onus of stopping the event propagation to not get the default browser behavior of scrolling to the top.