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
Component displays Height and Width on window resize
How to set property values using expression?
Create React App
Working with Forms, Inputs and onChange Events in ReactJs
How to render one component in another component in React JS?
React JS update Div content on click
Check checkbox is Checked or Unchecked
React Props
How to perform computation inside expression using ternary operator?
How to build and use a custom react component from scratch?