irfan
irfan

Reputation: 102

React Native | How to create dynamic state(hook)?

If control is provided, I have to generate a textinput. I need to put state into value and onChange. So I have to produce a dynamic state. How do i do this?

list.map(item =>{
//control true. i need creat textinput
if (control) {
       //I have to create the state here (ex. const[item.name, `set${item.name}`]=useState())
       return(
             <TextInput
                  onChangeText={(text) => ?}
                  value={?}
                  placeholder={item.name}
                  keyboardType={(item.input_type === "tel")}
             />
)}
})

Upvotes: 0

Views: 269

Answers (1)

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Try this way

constructor(props){
    super(props);
    this.state = {
      textInput : [],
      inputData : []
    }
  }

onTextChanged = (index, value) => {
    const inputData = [...this.state.inputData]; 
    inputData[index] = value;
}

const textInput = [...this.state.textInput];
    
list.map((item,index) =>{
  //control true. i need creat textinput
  if (control) {
  
    textInput.push(
    <TextInput
      value={this.state.inputData[index] || ''}
          placeholder={item.name}
          onChangeText={(text) => this.onTextChanged(index, text)} 
    />
    );
  }

});


 this.setState({ textInput });

Upvotes: 1

Related Questions