Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 623
dmigo Avatar asked Mar 09 '23 16:03

dmigo


1 Answers

Just adding on to this with what I think is the best solution these days.

This ignores blur events by using the Node.contains method to check whether the element is a descendant of that which is already focused.

handleBlur({ currentTarget, relatedTarget }) {
   if (currentTarget.contains(relatedTarget)) return;

   /* otherwise normal actions to perform on blur */

   console.log('blur');
}
handleFocus(e) {
   console.log('focus');
}
like image 92
Dawson Booth Avatar answered Apr 26 '23 10:04

Dawson Booth