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
- Prevent warning in React 16.9, see https://github.com/facebook/react/issues/16592 — committed to andrewringler/formik-json-schema by deleted user 5 years ago
- chore: 移除 javascript:; https://github.com/facebook/react/issues/16592 — committed to miaoxing/app by twinh 4 years ago
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:
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 tojavascript:void(0). What about just whitelisting this specific string? That would solve this usability problem while not introducing any security concerns.hrefattribute without value and equal sign worksTo make sure its cross browser compatible use unused ID.
See my reply in https://github.com/facebook/react/issues/16382#issuecomment-607252694.
@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 likeonClick. Using#gets that behavior but theonClickhandler then has the onus of stopping the event propagation to not get the default browser behavior of scrolling to the top.