Skip to content

Commit a06bf7b

Browse files
author
Julien Bouquillon
authored
fix: handle SSR
check if document exists before attaching/detaching listeners
1 parent c52e1af commit a06bf7b

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/KeyboardEventHandler.js

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,24 @@ export default class KeyboardEventHandler extends React.Component {
1414
}
1515

1616
componentDidMount() {
17-
document.addEventListener('keydown', this.handleKeyboardEvent, false);
18-
document.addEventListener('keyup', this.handleKeyboardEvent, false);
19-
document.addEventListener('keypress', this.handleKeyboardEvent, false);
17+
if (typeof document !== 'undefined') {
18+
document.addEventListener('keydown', this.handleKeyboardEvent, false);
19+
document.addEventListener('keyup', this.handleKeyboardEvent, false);
20+
document.addEventListener('keypress', this.handleKeyboardEvent, false);
2021

21-
const { isExclusive, isDisabled } = this.props;
22-
if (isExclusive && !isDisabled) {
23-
this.registerExclusiveHandler();
22+
const { isExclusive, isDisabled } = this.props;
23+
if (isExclusive && !isDisabled) {
24+
this.registerExclusiveHandler();
25+
}
2426
}
2527
}
2628

2729
componentWillUnmount() {
28-
document.removeEventListener('keydown', this.handleKeyboardEvent, false);
29-
document.removeEventListener('keyup', this.handleKeyboardEvent, false);
30-
document.removeEventListener('keypress', this.handleKeyboardEvent, false);
30+
if (typeof document !== 'undefined') {
31+
document.removeEventListener('keydown', this.handleKeyboardEvent, false);
32+
document.removeEventListener('keyup', this.handleKeyboardEvent, false);
33+
document.removeEventListener('keypress', this.handleKeyboardEvent, false);
34+
}
3135

3236
this.deregisterExclusiveHandler();
3337
}

0 commit comments

Comments
 (0)