3

I started learning Reactjs today and found an interesting fact (and din't find any relevant topic) that we must use preventDefault than using return false statement to prevent the default behavior: https://reactjs.org/docs/handling-events.html

But as far as I know, return false is equivalent to (from jQuery background):

// e.preventDefault();
// e.stopPropagation();
// stop function execution after return false
// stops the callback function

But I'm curious to know here how react has implemented so that we cannot use return false statement and we must use preventDefault to prevent the default behavior.

So, what's exactly difference between preventDefault and return false when it comes to reactjs? Why preventDefault is more robust than return false in reactjs?

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

3 Answers3

4

The events in react are not the native events of the browser, they are wrapped for your convenience.

Your event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

https://reactjs.org/docs/events.html

So when you do preventDefault, you are not calling the method of the native event directly, but instead, react takes care of you.

So returning false is returning false to reacts event and not the native event one, meaning, it doesn't really do anything...

Yftach
  • 712
  • 5
  • 15
2

When you call return false in the DOM, it has some "magical" behavior which is implicit instead of explicit. When you register an event callback in React, you are not explicitly setting an event handler in the DOM because React is an abstraction to the DOM. React elements are part of a "virtual DOM" and you are no longer working directly with the DOM, therefore event handlers have layers of abstraction between your component handler and the DOM element itself.

Could React have implemented their API in such a way that return false; mirrored this implicit behavior? Perhaps. But they have their own API and clearly chose not to.

Here is a good overview of how the DOM handles things when you return false.

Brian Genisio
  • 47,787
  • 16
  • 124
  • 167
1

Actually using return false from event handlers to prevent the default behavior has been deprecated since React 0.12.

So it's not an option of the most robust choice, you just can't use return false for this purpose in React.

You must call the event preventDefault explicitly, as explained in the documentation.