How to control defaultValue of React Native's <TextInput>?

user3259472 picture user3259472 · Oct 4, 2016 · Viewed 13.3k times · Source

I have a <TextInput/> with a defaultValue set up and a button where it would trigger and pass the defaultValue of <TextInput> elsewhere.

But how do I pass in the <TextInput/>'s defaultValue to the onPress method of <TouchableHighlight/>?

This is what I am trying to achieve:

changeName(text) {
    this.setState({nameNow: text}) //How can I immediately set the defaultValue='PassMeIn' to nameNow? Because this method would never be called unless text is changed within TextInput
}

sendOff() {
    //Would like to access the defaultValue='PassMeIn' here whenever sendOff() is called. How can I?
}

render() {

    return (
      <View>
            <TextInput 
                defaultValue='PassMeIn' 
                onChange={this.changeName} 
                value={this.state.nameNow}
            />
            <TouchableHighlight onPress={this.sendOff}/>
                <Text>Button</Text>
            </TouchableHighlight>
      </View>
    )
}

Answer

Brett DeWoody picture Brett DeWoody · Oct 4, 2016

For one, the render method can't return multiple nodes. I believe the <TextInput/> should be wrapped by the <TouchableHighlight/> component, like:

render() {

  return (
    <TouchableHighlight onPress={this.sendOff}>
      <TextInput 
        defaultValue='PassMeIn' 
        onChange={this.changeName} 
        value={this.state.nameNow}
      />
    </TouchableHighlight>    
  )
}

This will make it possible to pass a prop through from <TouchableHightlight> to <TextInput to use as the defaultValue and you'll have access to it in the <TouchableHighlight> component.