Created
January 28, 2020 23:25
-
-
Save ruswerner/d6b1f8d4b44243e53adc85c1f0a233ac to your computer and use it in GitHub Desktop.
Convert this React component to be a function component using hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, {Component, createRef} from 'react'; | |
| import PropTypes from 'prop-types'; | |
| export default class ConvertMe extends Component { | |
| ref = createRef(); | |
| state = { | |
| operator: '' | |
| }; | |
| static propTypes = { | |
| operand1: PropTypes.number, | |
| operand2: PropTypes.number | |
| }; | |
| static defaultProps = { | |
| operand1: 1, | |
| operand2: 2 | |
| }; | |
| componentDidMount() { | |
| if (this.ref.current) { | |
| this.ref.current.getElementsByTagName('h1')[0].innerText = 'Simple Equation App'; | |
| } | |
| } | |
| calculateResult(operand1, operand2) { | |
| switch (this.state.operator) { | |
| case '+': | |
| return operand1 + operand2; | |
| case '-': | |
| return operand1 - operand2; | |
| case '/': | |
| return operand1 / operand2; | |
| case '*': | |
| return operand1 * operand2; | |
| default: | |
| return '?'; | |
| } | |
| } | |
| handleChangeOperator(event) { | |
| this.setState({operator: event.target.value}); | |
| } | |
| render() { | |
| const {operand1, operand2} = this.props; | |
| const result = this.calculateResult(operand1, operand2); | |
| return ( | |
| <div ref={this.ref}> | |
| <h1>Loading...</h1> | |
| <div> | |
| <span>{operand1}</span>{' '} | |
| <select value={this.state.operator} onChange={this.handleChangeOperator.bind(this)}> | |
| <option>Select Operator</option> | |
| <option value="+">+</option> | |
| <option value="-">-</option> | |
| <option value="/">÷</option> | |
| <option value="*">×</option> | |
| </select>{' '} | |
| <span>{operand2}</span> | |
| {' = '} | |
| <em>{result}</em> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment