At the moment you are not utilizing any of the React’s data binding.
Best to use React’s state to hold the values of the total
and all the comp
inputs.
I’ve also used the .reduce method in order to calculate the total for each of the input fields’ values. But you can achieve the same thing with a for
loop.
JSFiddle: Alternative “calculateTotal” function with for loop
More information on Input handling in React
class App extends React.Component {
constructor() {
super();
this.state = {
total: 0,
numbers: {
comp1: 1,
comp2: 0,
comp3: 4,
comp4: 0,
comp5: 0,
comp6: 0
}
};
}
componentDidMount() {
// Calculates the total after component is mounted
this.setState({ total: this.calculateTotal(this.state.numbers) });
}
calculateTotal = (numbers) => {
return Object.entries(numbers).reduce((finalValue, [key, value]) => {
if (value === "") {
// if entered value is empty string "", omits it
return finalValue;
}
return finalValue + value;
}, 0);
}
handleTotal = (e) => {
const { value, name } = e.target; // gets the name and value from input field
const parsedValue = value === "" ? "" : parseFloat(value); // parses the value as a number or if empty treats it as empty string ""
this.setState((prevState) => {
// creates new immutable numbers object, using previous number values and the currently changed input value
const updatedNumbers = {
...prevState.numbers,
[name]: parsedValue
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
};
// calculates the new total from updated numbers:
const newTotal = this.calculateTotal(updatedNumbers);
return {
numbers: updatedNumbers,
total: newTotal
}
})
}
render() {
return (
<div>
<input type="number" name="comp1" onChange={this.handleTotal} value={this.state.numbers.comp1} />
<input type="number" name="comp2" onChange={this.handleTotal} value={this.state.numbers.comp2}/>
<input type="number" name="comp3" onChange={this.handleTotal} value={this.state.numbers.comp3}/>
<input type="number" name="comp4" onChange={this.handleTotal} value={this.state.numbers.comp4}/>
<input type="number" name="comp5" onChange={this.handleTotal} value={this.state.numbers.comp5}/>
<input type="number" name="comp6" onChange={this.handleTotal} value={this.state.numbers.comp6}/>
<div id="total">{this.state.total}</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>