Search code examples
react-nativetextinput

get value of input after button click


I am trying to get a value of an input after a button click. I found some things on the internet but I still haven't succeeded. I know it has something to do with setState. But I dont know how I can apply this in my code. Can anybody help me?


Solution

  • You can do it as following:

    constructor(props) {
      super(props);
      this.state = {
        value: ''
      }
    }
    onChangeText = (value) => {
      this.setState({ value });
    }
    
    onPress = () => {
      alert(this.state.value);
    };
    
    render() {
      return (
        <View>
          <TextInput
            onChangeText={this.onChangeText}
            value={this.state.value}
          />
          <Button
            onPress={this.onPress}
            title="Click"
          />
        </View>
      )
    }