I want to detect click outside of the React functional component.
Then I found the following article and implemented code accordingly.
But my code does not work. I understand the cause, however don't know solution.
import React from 'react';
import Foo from 'foo'; // <- Functional component in the node_modules
export default class extends React.PureComponent {
private readonly refRoot = React.createRef();
public componentDidMount() {
document.addEventListener('click', this.clickOutside);
}
public componentWillUnmount() {
document.removeEventListener('click', this.clickOutside);
}
private clickOutside(ev: MouseEvent) {
if (refRoot.current.contains(ev.target)) {
console.log('clicked outside.');
}
}
public render(){
return (
<Foo ref={this.refRoot}> // <- Doubt.
...
</Foo>
);
}
}
Because cannot use the ref attribute on function component.
Maybe able to solve it by wrapping it with a div
element, but I want to avoid complicating the stratum of the DOM any more when rendered to HTML.
What do you have any ideas?