react onclick event target code example
Example 1: react button onclick
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.sayHello = this.sayHello.bind(this);
}
sayHello() {
alert('Hello!');
}
return (
<button onClick={this.sayHello}>
Click me!
</button>
);
}
export default App;
Example 2: react onclick to make another button
import React from 'react';
const App = () => {
const message = () => {
console.log("Hello World!")
}
return (
<button onClick={message}> Press me to print a message! </button>
);
}
Example 3: react why onclick property function trigger without click
change:
<button type="button" onClick={this.myFunction(argument)}> myButton </button>
to this:
<button type="button" onClick={this.myFunction.bind(this, argument)}> myButton </button>
Example 4: 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);