How to correctly catch change/focusOut event on text input in React.js?

JavascriptReactjs

Javascript Problem Overview


I've got a form, in which I want to handle change event on text inputs, but React onChange triggering on key down (opposite to native JS, that triggers change event when an input field is out of focus).

Is there a React way to do what I want?

Javascript Solutions


Solution 1 - Javascript

If you want to only trigger validation when the input looses focus you can use onBlur.

>React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React. 2

Solution 2 - Javascript

Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.

Solution 3 - Javascript

You'd need to be careful as onBlur has some caveats in IE11 (https://stackoverflow.com/questions/41298948/how-to-use-relatedtarget-or-equivalent-in-ie, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).

There is, however, no way to use onFocusOut in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information. (see below for an update on this)

UPDATE:

As of React 17, the events have been updated - see PR for use focusin/focusout for onFocus/onBlur. However as the page listing breaking changes mentions: > Although React 17 switched from focus to focusin under the hood for the onFocus event, note that this has not affected the bubbling behavior. In React, onFocus event has always bubbled, and it continues to do so in React 17 because generally it is a more useful default. See this sandbox for the different checks you can add for different particular use cases.

Solution 4 - Javascript

JavaScript => React

onfocusout => onBlur

onfocusin => onFocus

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex SuslyakovView Question on Stackoverflow
Solution 1 - JavascriptDominicView Answer on Stackoverflow
Solution 2 - JavascriptjossieView Answer on Stackoverflow
Solution 3 - Javascriptkahlan88View Answer on Stackoverflow
Solution 4 - Javascriptmajid gabrloView Answer on Stackoverflow