I’m trying to calculate the sum of values inputted (the number of inputs change dynamically)
This is the function that returns the number of inputs:
const renderINP = () => { let td = []; for (let i = 1; i <= 3; i++) { td.push(<td key={i}><input className="example" type="text" defaultValue="0" id={i} /></td>); } return td; };
This is my component return
return ( <div> <table> <tbody> <tr> {renderINP()} <td>total<input id="total" type="text" defaultValue={total} /></td> </tr> </tbody> </table> </div> ); }
And this is the function that’s supposed to return the sum of values inputted from the user:
const [total,setTotal] = useState(0); const getSum = () => { let totalOfInps=0; for (let i = 1; i <= 3; i++){ let a=parseFloat(document.getElementById(i).value); totalOfInps+=a; } setTotal(totalOfInps); }
I’m trying to return the sum of all Inputed values In the Inputs who had id=”total” but It returns nothing ,also when I’m using console.log(totalOfInps) It shows nothing in the console,how I can get the sum of all Input values ?
Advertisement
Answer
import {useState} from 'react'; const sumAll = numList => numList.reduce((acc, num = 0) => acc + num, 0); const handleInputChange = (inputIndex, setValues) => event => { const value = parseFloat(event.target.value); if(!isNaN(value)){ setValues(previous => { const copy = previous.slice(); copy[inputIndex] = value; return copy; }); } } function App(){ const [values, setValues] = useState([]); const total = sumAll(values); return ( <div> <table> <tbody> <tr> { [1,2,3].map((id, index) => { const onChange = handleInputChange(index, setValues); return ( <td key={index}> <input className="example" onChange={onChange} type="text" defaultValue="0" id={id} /> </td> ); }) } <td>total<input id="total" type="text" defaultValue="0" value={total}/></td> </tr> </tbody> </table> </div> ); }; export default App;