how to add an event listener in react function code example
Example 1: 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 2: 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;