How to Pass input Field Data from Modal to the Container in react-Native?

javascript, react-native, reactjs

Solution

Let's assume that your Modal is filed separately in `/components/MyModal` to generalize things.

You can make your Modal call a function that you passed by props every time input text is changed. Here's a simple callback logic you can use.

Avoid using refs as much as you can.

import MyModal from '../components/MyModal';
...
class Home extends Component {
  onInputChanged = (changedText) => {
    console.log('This is the changed text: ', changedText);
  }

  render() {
    return (
      <View>
        ...
        <MyModal onInputChanged={this.onInputChanged} .../>
      </View>
    )
  }
}

// components folder
class MyModal extends Component {
  render() {
    return (
      <Modal
        visible = {this.props.visible}
        animationType="slide"
        transparent
        onRequestClose={() => {}} >
           <TextInput 
             style = {styles.inputBox}
             onChangeText={(changedText) => this.props.onInputChanged(changedText)} />
      </Modal>
    )
  }
}

Side Note: You can define MyModal stateless to make things a bit cleaner.

Problem

Here is what I am using: ``` <Modal visible = {this.props.visible} animationType="slide" transparent onRequestClose={() => {}} > <TextInput style = {styles.inputBox} ref = {this.props.destinatinon} /> </Modal> ``` and in the Container ``` <ExampleModal destination = {this.state.destination} > </ExampleModal> ``` I don't know how to pass data from Modal to Parent Component. Any kind of Tutorial or link is fine. Thanks in Advance.

Original source