1

I am getting an count from user selection - for example when user selects 5 means i will be getting

const count = 5;

And by keeping this, am dynamically creating textInput using for loop, and its working perfectly ! but how to store the values in state when user type ? I could not understand how to perform this action ! I have tried this , but it gives error saying value should not contain array as input,

 state = { userDetails: [] }

textHandler(texts){
        this.setState({...this.state.userDetails, texts})
    }

for (let i = 0; i < count; i++) {
            items.push(
    <TextInput 
           style={{ borderBottomWidth: 1, borderColor: '#f0eff4', height: 40 }}
           placeholder="Enter Name"
           onChangeText={text => this.textHandler(text)}
           value={this.state.userDetails}
   /> ) }
6
  • You create 5 input fields based on the count? Commented Oct 13, 2020 at 13:55
  • you want to store all values in the array or any value typed input? Commented Oct 13, 2020 at 13:55
  • yes right @TasosBu Commented Oct 13, 2020 at 13:55
  • As the count of textInput changes between 1 to 6, i thought array would help grouping up @NooruddinLakhani Commented Oct 13, 2020 at 13:56
  • How do you display the inputs? Do you use .map() method? Commented Oct 13, 2020 at 13:59

1 Answer 1

2

This might help (Updated)

class App extends Component {
  
  componentDidMount() {
    this.getDynamicInputs();
  }

  state = { userDetails: [], item_views: [] };

  updateState = (index, value) => {
    const userDetails = [...this.state.userDetails]; //make a copy of array
    userDetails[index] = value;
    this.setState({ userDetails: userDetails });
  };

  getDynamicInputs() {
    const inputData = [];
    for (let i = 0; i < count; i++) {
      inputData.push(
        <TextInput
          key={i}
          style={{ borderBottomWidth: 1, borderColor: "#f0eff4", height: 40 }}
          placeholder="Enter Name"
          onChangeText={(val) => this.updateState(i, val)}
          value={this.state.userDetails[i]}
        />
      );
    }
    this.setState({ item_views: inputData });
  }

  render() {
    console.log(this.state.userDetails);
    return <View style={styles.app}>{this.state.item_views}</View>;
  }
}

const styles = StyleSheet.create({
  app: {
    flex: 1,
    backgroundColor: "pink"
  }
});

export default App;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.