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