Created
December 11, 2018 22:34
-
-
Save mminer/6cf361ec08662d4ca12cc63ea6deaef5 to your computer and use it in GitHub Desktop.
React component that runs an action after no user activity is detected.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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