react handlers 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: handling event in jsx
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
Example 3: handler in react
import React, { Component } from "react";
class Form extends Component {
constructor() {
super();
this.state = {
username: "",
qty: "",
};
}
ChangeHandler = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = (e) => {
e.preventDefault();
console.log(this.state);
};
render() {
return (
<form onSubmit={this.submitHandler}>
<label htmlFor="username"> Name: </label>
<input type="text" name="username" id="username" onChange={this.ChangeHandler}/>
<label htmlFor="qty"> Quantity: </label>
<input type="text" name="qty" id="qty" onChange={this.ChangeHandler} />
<button> Submit </button>
</form>
);
}
}
export default Form;
Example 4: react event listener
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp