Question:
Within a React event handler, is there a convenient way to do e.preventeDefault
and e.stopPropagation
simultaneously (the way you used to be able to with a return false
)?
Background: React has started deprecating the use of:
return false;
inside event handlers as a means of achieving:
e.preventDefault();
e.stopPropagation();
This GitHub issue explains that the React team is trying to solve the problem of event callbacks which return false
incidentally (ie. without the intent to preventDefault/stopPropagation).
That makes perfect sense, and I understand the logic behind it, but ...
e.preventDefault();
e.stopPropagation();
is annoyingly more difficult to remember and write than return false
.
So, my question is: is there any convenient way to get return false
functionality inside a React event handler? For instance, is there some sort of e.stopBoth()
method, or a return React.PREVENT
constant, or any other way to get the old return false
functionality?
Or if not, is there any way to monkey patch such a function in?
Angular 2, Vue. js, Ember. js, NativeScript, and jQuery are the most popular alternatives and competitors to React.
To return nothing from a React component, simply return null . When null is returned from a React component, nothing gets rendered.
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form.
Recursion in React One of the cool things about React is that React components are essentially functions which return JSX. Therefore, just like with any other functions, React components can be recursive.
There isn't a definitive way of doing this, simply because it's not the behaviour the React team seems to want to encourage. There's speculation that return values from handlers could be used in some other way in future, but that sounds messy and counter-intuitive to me.
Anyway for our purposes you could:
a) Hack into the SyntheticEvent
stuff, but overriding/augmenting the React internals sounds like a really bad idea. SyntheticEvent
lets React normalize event handling.
b) Just create a simple helper function for this (hattip @octref):
// In some killEvent.js
module.exports = function(event) {
e.preventDefault();
e.stopPropagation();
}
// In some component file
var killEvent = require('./killEvent');
var Component = React.createClass({
... component implementation
myEventHandler = function(e) {
killEvent(e);
}
});
The exact implementation would depend on what module system you're using but hopefully you get the idea. I think this is the best approach as it is extremely simple, easy to do, and expresses what you're trying to do pretty clearly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With