john doe
john doe

Reputation: 816

e.target.value is undefined while adding dynamic input data in react

I need to add an input box (input-0, input-1...) each time a button is clicked.Following is the relevant code.

// State

      this.state = {
        newText: {}
      };

// Code to add dynamic input text

      addInputText = () => {
        let dynamicTextsNo = Object.keys(this.state.newText).length;
        let newInputId = dynamicTextsNo+1;
        let dynamicTextArr = this.state.newText;
        let newTextId = 'input-'+dynamicTextsNo;
        dynamicTextArr[newTextId] = '';
        let newState = { ...this.state, newText: dynamicTextArr }
        this.setState( newState );
      }

// Code to render dynamic input text.

      dynamicTextArea = () => {
        return Object.keys(this.state.newText).map( ( key ) => {
          return  ( <InputGroup key={key} borderType='underline'>
                      <Input placeholder='Type your text here' value={this.state.newText[key]} onChange={this.changeInput}/>
                    </InputGroup>
                  );
        });
      }

// Render function

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

// handle input

  changeInput = (e) => {
    console.log( e.target.value ); // **this comes out to be undefined.**
  }

Why is e.target.value in changeInput function undefined?

P.S. Jsfiddle link of the full code: https://jsfiddle.net/johnnash03/9by9qyct/1/

Upvotes: 0

Views: 5093

Answers (2)

jevakallio
jevakallio

Reputation: 35970

Unlike with the browser text input element, the event argument passed to React Native TextInput.onChange callback does not have a property called target.

Instead, use

<TextInput
  onChange={(event) => event.nativeEvent.text}
/>

or

<TextInput
  onChangeText={(text) => text}
/>

Upvotes: 11

KA01
KA01

Reputation: 4251

You must use bind like so <Input placeholder='Type your text here' value={this.state.newText[key]} onChange={this.changeInput.bind(this)}/>

Upvotes: 0

Related Questions