react-nativetextinputreact-state-management

updating state using name attribute on TextInput react-native


i'm attempting to update a state onChange within a form. When I type in the form my app crashes with this error

TypeError undefined is not an object react-native (evaluating e.target)

I'm trying to use [e.target.name] to select the appropriate state to update using my elements.

maybe i'm missing something small but I have pretty much the exact same code running in a react web project and it works fine?

here's my current form

export default class CreateNote extends Component {
  state = {
    modalVisible: false,
    title: "",
    who: "",
    time: ""
  };

  setModalVisible(visible) {
    this.setState({ modalVisible: visible });
  }

  onTextChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  createNoteView=()=>{
    if(this.state.modalVisible === true){
      return (
        <View style={{ marginTop: 10 }}>

              <Button title="cancel" onPress={()=>this.setState({modalVisible:false})}></Button>

                <TextInput
                  placeholder="title"
                  name = "title"
                  type="text"

                  onChange={()=>{this.onTextChange()}}
                />


                <TextInput
                  placeholder="who"
                  name = "who"
                  type="text"

                  onChange={()=>{this.onTextChange()}}
                />


                <TextInput
                  placeholder="when"
                  name = "time"
                  type="text"

                  onChange={()=>{this.onTextChange()}}
                />
        </View>
      )
    }

    return (
      <View style={{ marginTop: 22, width: 150 }}>
          <Button onPress={()=>{this.setModalVisible(!this.state.modalVisible)}} title="create"></Button>
      </View>
    )

  }


  render() {
    return(
      <View>
        {this.createNoteView()}
    </View>
    )

  }
}


Solution

  • You should use onChangeText method like below.

    onTextChange = (name) => (value) => {
      this.setState({ [name]: value });
    };
    
    ...other code...
    
    <TextInput
      placeholder="title"
      onChangeText={this.onTextChange("title")}
    />
    

    You can refer onChangeText here

    If you want to use onChange instead of onChangeText then you should use somthing like event.nativeEvent.text

    onTextChange = (name) => (event) => {
     this.setState({ [name]: event.nativeEvent.text });
    };
    
    ...other code...
    
    <TextInput
      placeholder="title"
      onChange={this.onTextChange("title")}
    />