I am trying to do following:
The user can select a calculation from the dropdown menu. The selected numbers(from calculation) appear in the input fields and the user can change the calculation. The modified calculation is displayed after pressing the "Add" button. Also the modified calculation should shown in red color in the dropdown menu.
I managed to get the calculation right, but the selected numbers doesn't appear in the input fields. What I have to do to update the values to the input fields?
Here is my code:
import React from 'react';
export default class Lisatehtava1 extends React.Component {
constructor(props) {
super(props);
this.state = {
num1: 0,
num2: 0,
total: 0,
results: [],
}
}
handleChange = (e) => {
const { name, value } = e.target;
this.setState({
[name]: value
})
}
add = () => {
const { num1, num2 } = this.state;
this.setState({
total: (parseInt(num1) + parseInt(num2))
}, () => {
let result = { num1: this.state.num1, num2: this.state.num2, total: this.state.total };
const t = [...this.state.results, result];
this.setState({ results: t }, () => {
this.setState({ num1: "" }, () => {
this.setState({ num2: "" });
});
});
})
}
render() {
let dropdown = this.state.results.map((item, id) => {
return <option key={id}>{item.num1} + {item.num2} = {item.total}</option>
});
return (
<div>
<div>
<label>Numero 1</label>
<input type="text" name="num1" onChange={this.handleChange} />
</div>
<div>
<label>Numero 2</label>
<input type="text" name="num2" onChange={this.handleChange} />
</div>
<button onClick={this.add}>Add</button>
<div><select onChange={this.handleChange}>{dropdown}</select></div>
</div>
);
}
}