add event listener to react element code example
Example 1: event listener for functional component
import React, { useEffect } from 'react';
const Component = (props) => {
useEffect(() => {
window.addEventListener('scroll', handleScroll);
});
useEffect(() => {
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
function handleScroll() {
let scrollTop = window.scrollY;
}
return ()
}
Example 2: event listener in react
var Box = React.createClass({
getInitialState: function() {
return {windowWidth: window.innerWidth};
},
handleResize: function(e) {
this.setState({windowWidth: window.innerWidth});
},
componentDidMount: function() {
window.addEventListener('resize', this.handleResize);
},
componentWillUnmount: function() {
window.removeEventListener('resize', this.handleResize);
},
render: function() {
return <div>Current window width: {this.state.windowWidth}</div>;
}
});
ReactDOM.render(<Box />, mountNode);
Example 3: react event listener
import React from 'react';
class App extends React.Component {
handleChange = e => {
console.log(`${e.target.value}`)
}
render() {
return (
<div className="App">
<input type="text" name="input" id="" placeholder="" onChange={this.handleChange}/>
</div>
);
}
}
export default App;
Example 4: react event listener
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp