react handler code example
Example 1: react button example
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 button onclick
import React from 'react';
function App() {
function sayHello() {
alert('Hello!');
}
return (
<button onClick={sayHello}>
Click me!
</button>
);
}
export default App;
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;