How to implement onBlur/onFocus for a div with nested input fields?

dmigo picture dmigo · Jul 6, 2017 · Viewed 10.1k times · Source

There is a <div> and a couple of nested <input>s. onBlur fires every time user clicks on one of the <input>s.
This is a bit frustrating that onBlur happens when I hit something inside the div. After an hour of searching I still wasn't able to find any good solution.
This sample of code shows what I'm talking about:

class Thing extends React.Component {
  handleBlur(e) {
    console.log('blur');
  }
  handleFocus(e) {
    console.log('focus');
  }
  render() {
    return (
      <div onFocus={this.handleFocus} onBlur={this.handleBlur} tabIndex="1">
        <div>
          <input type="text" value="Hello," />
        </div>
        <div>
          <input type="text" value="Thing" />
        </div>
      </div>
    );
  }
}

You may play around with the code over here.
However my ultimate goal is to make this thing working properly.

Answer

qiAlex picture qiAlex · Jul 6, 2017

You may want to ignore extra blur events.

handleBlur(e) {
   if (e.target.tagName == "INPUT") {
      return;
   }
   console.log('blur');
}
handleFocus(e) {
   console.log('focus');
}