There are 3 numeric input fields: a, b and c.
When user edits "a" or "b" then "c" should be calculated as a*b.
When "c" is edited then look which field was edited most recently:
if "a" then "b" = c/a
if "b" then "a" = c/b
The following working code allows to edit a, b and c.
I cannot figure out how to implement the calculation a or b if c is edited.
import React, { useState } from 'react';
const Calc = () => {
const [values, setValues] = useState( { a: 3, b: 2, c: 6 });
const handleChange = (e) => {
const { name, value } = e.target;
setValues({ ...values, [name]: value });
};
return (
<div>
<div className="row">
<label htmlFor="a">a</label>
<input type="number" id="a" name="a" onChange={handleChange} value={values.a} />
</div>
<div className="row">
<label htmlFor="b"> b </label>
<input type="number" id="b" name="b" onChange={handleChange} value={values.b} />
</div>
<div className="row">
<label htmlFor="c"> c </label>
<input type="number" id="c" name="c" onChange={handleChange} value={values.c} />
</div>
</div>
);
};
To make multiplication for calculating "c" I added to the end of handleChange()
if (name === 'a') {
setValues({ ...values, a: value, c: value * values.b });
}
if (name === 'b') {
setValues({ ...values, b: value, c: value * values.a });
}
but I do not know how to calculate "a" or "b" when "c" is edited because I need to decide which field "a" or "b" needs to be calculated based on last edit event between these 2.