How can I add a click handler to BODY from within a React component?
React is just JavaScript so attaching a click handler to any element is done as normal by using addEventListener()
. Doing this in componentDidMount
is normally very nice and tidy and clean up after yourself in componentWillUnmount
by removing the added event handler.
var Component = React.createClass({
componentDidMount: function () {
document.body.addEventListener('click', this.myHandler);
},
componentWillUnmount: function () {
document.body.removeEventListener('click', this.myHandler);
},
myHandler: function () {
alert('click');
},
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
It's help who used function based components:
import React, { useEffect } from 'react';
const ZSideBar = (props) => {
useEffect(() => {
document.body.addEventListener('click', closeSidemenu );
return function cleanup() {
window.removeEventListener('click', closeSidemenu );
}
},[]);
let closeSidemenu = () => {
document.getElementById("sidebar-tree").style.left = "-310px";
}
return (
<div></div>
)
}