Solution 1 :

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>

Solution 2 :

You just re-assign variable in every iteration of a loop. Change to smth like this:

handleTotal = e => {  
    // Grab all inputs that start with ID 'comp'
    let inputs = document.querySelectorAll('[id^="comp"]');

    // Trying to loop through the values and get the sum of all inputs
    let totalVal=0
    for (var i = 0; i < inputs.length; i++) {
        totalVal += inputs[i].value
        console.log(totalVal);
    }

    //Trying to grab total values of all inputs and put in element 
    document.getElementById('total').innerHTML = totalVal;
}

+= operator just adds value of next element to total variable. it is equal to totalVal = totalVal + inputs[i].value

Solution 3 :

const handleFormSubmit = (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    let total = 0;
    for (let [key, value] of formData.entries()) {
        total += value * 1;
    }
    document.querySelector('#total').textContent = total;
};

document.addEventListener('DOMContentLoaded', () => {
  const form = document.querySelector('form');
  form.addEventListener('submit', handleFormSubmit, false);
});
<form>
  <input type="number" id="comp1" name="comp1" />
  <input type="number" id="comp2" name="comp2" />
  <input type="number" id="comp3" name="comp3" />
  <input type="number" id="comp4" name="comp4" />
  <input type="number" id="comp5" name="comp5" />
  <input type="number" id="comp6" name="comp6" />
  <button type="submit">submit</button>
</form>
<span>total</span>
<div id=total></div>

Problem :

I am attempting to in React JS to get the sum of a group inputs, and put the sum of their total values in a div tag.

I am trying to run this event whenever a user types in any of the inputs

The problem is I am sure React has a proper way to do this!

This is my feeble attempt (please go easy – I am new to coding 🙂

HTML

<input type="number" id="comp1" name="comp1" onChange={this.handleTotal} />
<input type="number" id="comp2" name="comp2" onChange={this.handleTotal} />
<input type="number" id="comp3" name="comp3" onChange={this.handleTotal} />
<input type="number" id="comp4" name="comp4" onChange={this.handleTotal} />
<input type="number" id="comp5" name="comp5" onChange={this.handleTotal} />
<input type="number" id="comp6" name="comp6" onChange={this.handleTotal} />
<div id=total></div>

JS

handleTotal = e => {  
    // Grab all inputs that start with ID 'comp'
    let inputs = document.querySelectorAll('[id^="comp"]');

    // Trying to loop through the values and get the sum of all inputs
    for (var i = 0; i < inputs.length; i++) {
        let totalVal = inputs[i].value
        console.log(totalVal);
    }

    //Trying to grab total values of all inputs and put in element 
    document.getElementById('total').innerHTML = totalVal;
}

By