Skip to content

Instantly share code, notes, and snippets.

@ruswerner
Created January 28, 2020 23:25
Show Gist options
  • Select an option

  • Save ruswerner/d6b1f8d4b44243e53adc85c1f0a233ac to your computer and use it in GitHub Desktop.

Select an option

Save ruswerner/d6b1f8d4b44243e53adc85c1f0a233ac to your computer and use it in GitHub Desktop.
Convert this React component to be a function component using hooks
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="/">&divide;</option>
<option value="*">&times;</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