How to use onChange and onClick event in React JS?
Example
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = {
number1: 0,
number2: 0,
result: 0
};
}
handleOnChange = e => {
const { target: { value, name } } = e;
this.setState({
[name]: Number(value)
});
}
handleResult = e => {
this.setState({
result: this.state.number1 + this.state.number2
});
}
render() {
return (
<div className="Calculator">
<input onChange={this.handleOnChange} name="number1" type="text" value={this.state.number1} />
{' + '}
<input onChange={this.handleOnChange} name="number2" type="text" value={this.state.number2} />
<p><button onClick={this.handleResult}>=</button></p>
<p className="result">{this.state.result}</p>
</div>
);
}
}
export default App;
Most Helpful This Week
How to render raw HTML content in React JS?
Embed JavaScript Expressions in JSX
Working with Forms, Inputs and onChange Events in ReactJs
React Elements
React JS update Div content on click
How to use arrow function in React stateless components?
React JS onClick event handler
How to render one component in another component in React JS?
onClick Event binding and get event name in ReactJs
React JSX