Search code examples
javascriptiosreact-nativetextinput

React-Native: Access TextField value in another class


As an iOS dev I'm struggling a bit with react native.

I have two components inside different classes:

Component A is a view with a TextInput

class A extends Component<Props>{
    state = {
        textFieldValue: ""
    };  
    render() {
        return (
            <View>
                <TextInput placeholder={this.props.placeholderText}
                            ref={textField => {
                                this.textField = textField;
                            }}
                            value={this.state.textFieldValue}
                            onChange={e => this.setState({ textFieldValue: e.target.value})}/>
            </View>
        );}
}

Component B uses A in it's view

class B extends Component<Props>{
        render() {
            return (
                <View>
                   <A placeholder={"test"}/>
                   <TouchableOpacity onPress={() => {
                                //show text of input A here
                            }}>
                        <View>
                            <Text>{text}</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            );}
    }

How can I access the value/state with the value of the TextInput in A from B to show it on the button press?


Solution

  • Try this on Class B

        class B extends Component<Props>{
      render() {
          return (
              <View>
                 <A placeholder={"test"} ref={c => this.textRef = c}/>
                 <TouchableOpacity onPress={() => {
                              //show text of input A here
                              alert(this.textRef.state.textFieldValue)
                          }}>
                      <View>
                          <Text>{text}</Text>
                      </View>
                  </TouchableOpacity>
              </View>
          );}
    }
    

    Access reference of class A through ref props, then get its own state.