Pass value to TextInput onPress

1.9k views Asked by At

My Component is :

class TextInputComp extends Component {
  constructor(props){
    super();
    this.state = { thetext: '' }
  }

  submitText = (text) => {
    Alert.alert("Text Submitted!", text);
  }

  render() {
    const renData = this.props.people((data, index) => {
      return (
         <View key={index} style={styles.card}>
            <Text style={styles.names}> ID: {data.id} - Name: {data.name} </Text>
           <TouchableOpacity
              onPress={()=>this.refs.MyBox.focus()} >
              <Text>Open</Text>
           </TouchableOpacity>
         </View> 
           )
        });
 return (
      <View style={mystyles1.container}>
         {renData}
        <View>
        <TextInput
          ref='MyBox'
          style={{height: 40}} 
          onChangeText={(thetext) => this.setState({thetext})}
        />
          <TouchableOpacity
            onPress = { () => this.submitText(this.state.thetext) }>
               <Text style = {styles.ButtonText}> Submit </Text>
            </TouchableOpacity>
        </View>
      </View>
    );
  }
}

I can show the data from {redData} and focus on TextInput when clicked on Open. I want to pass a value to the TextInput. Say I want to pass the data.name, so when onPress on Open, I want the data.name to be already at the start of the TextInput so I can pass it to the this.state.thetext.

How can I achieve this? Many thanks.

1

There are 1 answers

2
Prakash Sharma On BEST ANSWER

You can make your TextInput controlled. For that you can pass value prop to TextInput like this

<TextInput
  ref='MyBox'
  style={{height: 40}} 
  value={this.state.thetext}
  onChangeText={(thetext) => this.setState({thetext})}
  />

Now on focus, all you have to do is to set the thetext state with the value you want to display in TextInput like this

<TouchableOpacity
   onPress={()=>{this.refs.MyBox.focus(); this.setState({thetext: data.name})}} >
   <Text>Open</Text>
</TouchableOpacity>