Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing ref from sibling

I am using the library react-native-dropdownaler and when I am creating the ref for it in App instead of adding the component in each screen I want to simply pass its ref to my Router and use it later. the problem with passing its ref to the sibling is - they both render together so when I am passing the ref its still undefined

render() {
  return (
    <View style={styles.container}>
      <StatusBar />
       <Router alertRef={this.alertRef}/>
       <DropdownAlert ref={ref => (this.alertRef = ref)} />
    </View>
  );
}
like image 393
obiwankenoobi Avatar asked Jun 16 '26 09:06

obiwankenoobi


2 Answers

You can use the createRef API to create a ref. The current property will still not be set until after the first render though.

class App extends React.Component {
  alertRef = React.createRef();

  render() {
    return (
      <View style={styles.container}>
        <StatusBar />
        <Router alertRef={this.alertRef} />
        <DropdownAlert ref={this.alertRef} />
      </View>
    );
  }
}
like image 63
Tholle Avatar answered Jun 18 '26 00:06

Tholle


I'd pass down the component itself instead and mirror the method in the component:

render() {
 return (
  <View style={styles.container}>
    <StatusBar />
    <Router alertRef={this}/>
    <DropdownAlert ref={ref => (this.alertRef = ref)} />
  </View>
 );
}

alertWithType(type, title, message) {
  this.alertRef.alertWithType(type, title, message);
}
like image 27
Jonas Wilms Avatar answered Jun 18 '26 00:06

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!