Home > OS >  how to get the value of the textinnput when submit button is pressed
how to get the value of the textinnput when submit button is pressed

Time:09-21

I just started learning react native, after i learned reactJs. I was wondering how to set the value of the TextInput when the button is pressed as the state value "message", and not to have it hard coded as i have it at the moment...

export default class Writing extends Component {
    constructor() {
      super();
      this.state={
        message: "",
      };
    } 
    
    onSend = () => {
      this.setState({ message: "Hello world!" });
      alert(this.state.message)
    }
      
    render(){
      return (
        <View>
          <TextInput
            style={styles.input}
            placeholder="Your message"
            onChangeText={this.state.message}
          />
          <Button
            title="Submit"
            onPress={this.onSend}
          />
        </View>
      )
    }
}```

CodePudding user response:

It is the same in react-native as in react. So you should do the same things i.e:

      <TextInput
        style={styles.input}
        placeholder="Your message"
        onChangeText={(text)=>this.setState({message:text})}
      />

CodePudding user response:

You need value props for TextInput. You may refer to the document written by React Native. https://reactnative.dev/docs/textinput

You can modify your code like this.

constructor() {
  super();
  this.state={
    message: "",         //This stores what you want to replace when button is pressed
    textInputValue: "",  //This stores textinput value
  };
} 

onSend = () => {
  //Set text input value by state 'message'
  this.setState({ textInputValue : this.state.message});
}

<TextInput
    value={this.state.textInputValue}   //This controls textinput value
    style={styles.input}
    placeholder="Your message"
    onChangeText={(text)=>{this.setState({textInputValue: text}}
/>

CodePudding user response:

Replace your onSend with the below code. onChangeText never holds the state, it is used to change the state. So, please replace your TextInput component with the below code.

TextInput

<TextInput
   value = {this.state.message}
   style={styles.input}
   placeholder="Your message"
   onChangeText={(result) => {
      this.setState({ message: result })
    }}
 />

onSend

onSend = () => {
    alert(this.state.message)
}
  • Related