Skip to content

Instantly share code, notes, and snippets.

@mminer
Created December 11, 2018 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mminer/6cf361ec08662d4ca12cc63ea6deaef5 to your computer and use it in GitHub Desktop.
Save mminer/6cf361ec08662d4ca12cc63ea6deaef5 to your computer and use it in GitHub Desktop.
React component that runs an action after no user activity is detected.
import PropTypes from 'prop-types';
import { Component } from 'react';
const eventListenerOptions = { capture: true, passive: true };
// Events that signify that the user is still active.
const eventNames = ['keydown', 'mousedown', 'touchstart'];
class InactivityReset extends Component {
constructor(props) {
super(props);
this.resetTimeout = this.resetTimeout.bind(this);
this.timeoutHandle = null;
}
componentDidMount() {
eventNames.forEach(eventName =>
window.addEventListener(
eventName,
this.resetTimeout,
eventListenerOptions
)
);
this.resetTimeout();
}
componentWillUnmount() {
eventNames.forEach(eventName =>
window.removeEventListener(
eventName,
this.resetTimeout,
eventListenerOptions
)
);
}
render() {
return this.props.children;
}
resetTimeout() {
const { onReset, timeout } = this.props;
if (timeout <= 0) {
return;
}
if (this.timeoutHandle) {
window.clearTimeout(this.timeoutHandle);
}
this.timeoutHandle = window.setTimeout(onReset, timeout);
}
}
InactivityReset.propTypes = {
children: PropTypes.node.isRequired,
onReset: PropTypes.func.isRequired,
timeout: PropTypes.number.isRequired,
};
export default InactivityReset;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment