1
votes

I am writing a React component (v0.14.7+) that needs to call an onBlur callback (passed in via props) when the cursor leaves the component (via tab, mouse click or touch event).

The challenge is that this component has two input tags. If the onBlur happens with the first I should not call the onBlur handler if the element gaining focus is the second input tag. In other words I should only fire onBlur if the focus as left BOTH of the input elements.

I am looking for a clean solution to this problem that works cross-browser and ideally using just the React api/synthetic events. I.e. without looking at the native event unless I really have to. How should I do this?

Note that the onFocus event fires after the onBlur event so I can't do this by just keeping track of which field has focus. Also the document.activeElement at the time the onBlur event fires seems to return the document object and not the active element.

1

1 Answers

2
votes

I would use timeout to postpone change of hasFocus (let's say) for a while. If there is another attempt to update hasFocus, clear pending scheduled setState attempt. Do not forget to clear timeout when unmounting component

See working example. Watch console, you won't get "true" and "false" printed when focusing from first <---> seconds input.

https://jsfiddle.net/69z2wepo/38136/