I am working on a form that is filled by the user and should update other input fields at the same time according to the entered data. For instance, If we have 3 input fields of number 1, number 2 and their sum. How can we update each one of them as the user types? The problem with my current implementation is that it does not always work. If a field id rendered automatically and I try to change it manually, everything stops. In other words, the app is not taking into consideration the values calculated from the formulas, they are just rendered in the fields.
import React, { useState } from 'react';
const Calculations = () => {
const [values,setValues]=useState({first:"",second:"",sum:""})
const [first,setFirst]=useState('')
const [second,setSecond]=useState('')
const [sum,setSum]=useState('')
const onChange=(e)=>{
let name=e.target.name;
let value=e.target.value;
const newValues = {
...values,
[name]: value
}
setValues(newValues)
calcSum(newValues)
calcfirst(newValues)
calcSecond(newValues)
}
const calcSum = (newValues) => {
const { first,second} = newValues;
const newSum = parseInt(first,10)+parseInt(second,10)
setSum(newSum)
}
const calcfirst = (newValues) => {
const { sum,second} = newValues;
const newFirst = parseInt(sum,10)-parseInt(second,10)
setFirst(newFirst)
}
const calcSecond = (newValues) => {
const { sum,first} = newValues;
const newSecond = parseInt(sum,10)-parseInt(first,10)
setSecond(newSecond)
}
return ( <form>
<div style={{display:"flex",flexDirection:"column"}}>
<label htmlFor="first">First</label>
<input onChange={onChange} defaultValue={first} name='first' id="first" type="number"/>
<label htmlFor="second">Second</label>
<input onChange={onChange} defaultValue={second} name="second" id="second" type="number"/>
<label htmlFor="sum">Total</label>
<input onChange={onChange} defaultValue={sum} id="sum" name="sum" type="number"/>
</div>
</form> );
}
export default Calculations;