0

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?

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this was my guess too but it returns undefined
Ok I used onChange instead of onChangeText... it works now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.