I have been building component listening to clicks on the whole document and stumbled upon IE11 issue.
I wrote a couple of simple components to reproduce this issue.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
show: false
}
}
render() {
return (
<div>
<button
onClick={() => this.setState({
show: !this.state.show
})}
>
Toggle
</button>
<div>
{this.state.show && (
<Component />
)}
</div>
</div>
)
}
}
class Component extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
console.log('listener added')
document.addEventListener('click', this.handleClick)
}
componentWillUnmount() {
console.log('listener removed')
document.removeEventListener('click', this.handleClick)
}
handleClick() {
console.log('clicked!');
const node = ReactDOM.findDOMNode(this);
}
render() {
return <div>Component</div>
}
}
ReactDOM.render(
<App /> ,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
So, the Component component adds click listener to document, and App component takes care of mounting and unmounting Component.
Everything works perfect in Chrome and Firefox, when Component is mounted event listener is applied and when it is unmounted listener is removed.
In IE11 however, when listener is removed, handler function is still called after and error is thrown because it tries to findDOMNode of unmounted component. This may not be a breaking issue, but it still bugs me and I would like to know if there is any workaround.
Also, note - stopping propagation via event.stopPropagation is not an option because in my app Component can be unmounted with many ways, button click is just an example
It seems to be a bug in IE11. A few options:
1.
Using window.addEventListener/window.removeEventListener vs. document.addEventListener/document.removeEventListener should work.
2.
I've seen other solutions wrap the handler with isMounted:
if (this.isMounted) {
const node = ReactDOM.findDOMNode(this);
}
But isMounted is deprecated and gives a warning. It is considered an antipattern.
3.
A current hack would be to create your own isMounted. Something like:
componentDidMount() {
this.mounted = true;
document.addEventListener('click', this.handleClick)
}
componentWillUnmount() {
this.mounted = false;
document.removeEventListener('click', this.handleClick)
}
handleClick() {
if (this.mounted) {
const node = ReactDOM.findDOMNode(this);
}
}
But this only gets around the isMounted console warning.