Skip to content

Instantly share code, notes, and snippets.

@jessebeach
Created April 22, 2017 22:44
Show Gist options
  • Save jessebeach/7e3d25ab587ae06a30f03d8d3e1adeef to your computer and use it in GitHub Desktop.
Save jessebeach/7e3d25ab587ae06a30f03d8d3e1adeef to your computer and use it in GitHub Desktop.
class Grid extends React.Component {
_timeoutID;
constructor() {
this.state = {
isManagingFocus: false,
};
}
render() {
return (
<div
role="grid"
onBlur={this._onBlur}
onFocus={this._onFocus}
>{this.props.children}</div>
);
}
_onBlur() {
this._timeoutID = setTimeout(() => {
if (this.state.isManagingFocus) {
this.setState({
isManagingFocus: false,
});
}
}, 0);
}
_onFocus() {
clearTimeout(this._timeoutID);
if (!this.state.isManagingFocus) {
this.setState({
isManagingFocus: true,
});
}
}
}
@smitpatelx
Copy link

Functional approach :

import { useState } from "react";

const FocusOutside = ({clickedOutside, ...props})=>{
  
  let _timeoutID;

  const [IsManagingFocus, setIsManagingFocus] = useState(false);

  const _onBlur = ()=>{
    _timeoutID = setTimeout(() => {
      if (IsManagingFocus) {
        setIsManagingFocus(false)
        clickedOutside()
      }
    }, 0);
  }

  const _onFocus = ()=>{
    clearTimeout(_timeoutID);
    if (!IsManagingFocus) {
      setIsManagingFocus(true)
    }
  }

  return (
      <div
        onBlur={_onBlur}
        onFocus={_onFocus}
        >{props.children}</div>
    );
}

export default FocusOutside;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment