Simulating Events
In this recipe, we are going to learn how to simulate theonClick
andonChange
events on a simple Calculator component.
How to do it...
We will re-use the code of the last recipe (Repository: Chapter12/Recipe3/debugging
):
- We will create a simple
Calculator
component to sum two values (input) and then we will get the result when the user clicks on the equals (=
) button:
import React, { Component } from 'react'; import styles from './Calculator.scss'; class Calculator extends Component { state = { number1: 0, number2: 0, result: 0 }; handleOnChange = e => { const { target: { value, name } } = e; this.setState({ [name]: value }); } handleResult = () => { this.setState({ result: Number(this.state.number1) + Number(this.state.number2) }); } render() { return ( <div className={styles.Calculator}> <h1>Calculator</h1> <input name="number1" value={this.state.number1} onChange={this.handleOnChange...