How to return the sum of all the dynamic TextInput fields in react native

Viewed 271
import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  TouchableOpacity,
  TextInput,
} from 'react-native';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      InputArr: [],
      FinalVal: [],
      Sum: 0,
    };
  }

  AddNewView = () => {
    this.setState({
      InputArr: [
        ...this.state.InputArr,
        <TextInput
          style={styles.FieldNew}
          keyboardType="numeric"
          onChangeText={(e) =>
            this.setState({ FinalVal: this.state.FinalVal.concat(e) })
          }
        />,
      ],
    });
  };

  CalBtnFunc = () => {
    var Total = 0;
    for (let i = 0; i <= this.state.FinalVal.length; i++) {
      Total += Number(this.state.FinalVal[i]);
    }
    this.setState({ Sum: Total });
  };

  render() {
    return (
      <View style={styles.container}>

        <TouchableOpacity style={styles.AddBtn} onPress={this.AddNewView}>
          <Text>Click to add new Field</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.AddBtn} onPress={this.CalBtnFunc}>
          <Text>Calculate</Text>
        </TouchableOpacity>

        <View>{this.state.InputArr}</View>

        <Text>Sum is : {this.state.Sum}</Text>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },

  AddBtn: {
    marginTop: 30,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },

  FieldNew: {
    borderColor: 'red',
    borderWidth: 1,
    marginBottom: 5,
  },
});

export default App;

I'm trying to make a program where the user can add TextInput fields dynamically and once the user clicks on calculating it should return the sum of all the values in all the TextInput fields.

*TextInput will only accept numeric values.

I have written the code but it's not working as I want it to be.

What I have done:

when click to add new field is clicked it appends a TextInput field to the state variable called InputArr(Array) and all the values of the TextInput field are stored in a state variable called FinalVal. On clicking the calculate button I have used a for loop to iterate over all the values present in the FinalVal array and sum it and store it in another state variable called Sum.

Here's the Code Link (Snack) : Click to view code

1 Answers

I have changed AddNewView and CalBtnFunc to make it work. Let's get through the changes I've made:

const CustomTextInput = ({name, _onChange}) => (
  <TextInput
    style={styles.FieldNew}
    keyboardType="numeric"
    onChangeText={(value) => {
      _onChange(value, name)
    }}
  />
);
  1. Made a custom Component "CustomTextInput" to pass through it a name to be able to differentiate the different inputs that get added dynamically and a custom onChange function (_onChange).

AddNewView becomes:

AddNewView = () => {
    this.setState({
      InputArr: [
        ...this.state.InputArr,
        <CustomTextInput
          name={this.state.InputArr.length + 1}
          _onChange={(value, name) => {
            this.HandleChange(value, name)
          }}
        />,
      ],
    });
  };
HandleChange = (value, name) => {
    const newFinalVal = {...this.state.FinalVal};
    newFinalVal[`${name}`] = value

    if (!isNaN(value)) this.setState({ FinalVal: newFinalVal})
 }
  1. Inside the function that handles the change instead of having FinalVal as an array, I made it an object to store individually the value of each input. The object FinalVal will look something like this {"1": 10, "2": 7, ....}
  CalBtnFunc = () => {
    var Total = 0;
    for (const [key, value] of Object.entries(this.state.FinalVal)) {
      Total += Number(value);
    }
    this.setState({ Sum: Total });
  };
  1. Now since we have an array instead of an object, I changed CalBtnFunc to loop through it with for (const of) syntax instead of a normal loop.

Here's a working snack: https://snack.expo.dev/@whygee/grounded-bagel

Related