After updating to React 16.9.0 I'm getting big warnings like this:
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:;".
It comes from code like this:
const Component = ({someAction}) => (
<a href="javascript:void(0)" onClick={someAction}>click me</a>
);
Looking at the StackOverflow question about which “href” value should I use for JavaScript links in HTML it seems most of you agree javascript:void(0)
is the best option, which will be no longer possible in React 16.9.0.
Just replacing with href="#"
is problematic, since the browser will scroll to the top of the page and change the displayed URL. Especially if you use hash-links for routing this is very problematic.
I could update my whole codebase to have e.preventDefault();
in each and every event handler, but this seems hard to do, especially when the event handlers are automatically created from Redux action creators or hooks. I do not look for the answer "just include e.preventDefault();
" everywhere!
Also using a <button>
means I have to deal with lots of unwanted styles applied.
So I was wondering: Are there any solutions specific to the library React to get a working <a>
link that just triggers an action without side effects? I want to change the code as little as possible and get rid of deprecation warnings.