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:
JavaScript
x
8
1
const renderINP = () => {
2
let td = [];
3
for (let i = 1; i <= 3; i++) {
4
td.push(<td key={i}><input className="example" type="text" defaultValue="0" id={i} /></td>);
5
}
6
return td;
7
};
8
This is my component return
JavaScript
1
14
14
1
return (
2
<div>
3
<table>
4
<tbody>
5
<tr>
6
{renderINP()}
7
<td>total<input id="total" type="text" defaultValue={total} /></td>
8
</tr>
9
</tbody>
10
</table>
11
</div>
12
);
13
}
14
And this is the function that’s supposed to return the sum of values inputted from the user:
JavaScript
1
11
11
1
const [total,setTotal] = useState(0);
2
3
const getSum = () => {
4
let totalOfInps=0;
5
for (let i = 1; i <= 3; i++){
6
let a=parseFloat(document.getElementById(i).value);
7
totalOfInps+=a;
8
}
9
setTotal(totalOfInps);
10
}
11
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
JavaScript
1
51
51
1
import {useState} from 'react';
2
3
const sumAll = numList => numList.reduce((acc, num = 0) => acc + num, 0);
4
5
const handleInputChange = (inputIndex, setValues) => event => {
6
const value = parseFloat(event.target.value);
7
if(!isNaN(value)){
8
setValues(previous => {
9
const copy = previous.slice();
10
copy[inputIndex] = value;
11
return copy;
12
});
13
}
14
}
15
16
17
function App(){
18
const [values, setValues] = useState([]);
19
const total = sumAll(values);
20
21
return (
22
<div>
23
<table>
24
<tbody>
25
<tr>
26
{
27
[1,2,3].map((id, index) => {
28
const onChange = handleInputChange(index, setValues);
29
return (
30
<td key={index}>
31
<input
32
className="example"
33
onChange={onChange}
34
type="text"
35
defaultValue="0"
36
id={id}
37
/>
38
</td>
39
);
40
})
41
}
42
<td>total<input id="total" type="text" defaultValue="0" value={total}/></td>
43
</tr>
44
</tbody>
45
</table>
46
</div>
47
);
48
};
49
50
export default App;
51