Reputation: 1582
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>
);
}
Upvotes: 3
Views: 752
Reputation: 1582
The solution I end up with is :
class App extends Component {
constructor(props)
super(props)
this.state = {alertRef:null}
componentDidMount() {
this.setState({alertRef:this.alertRef})
}
render() {
return (
<View style={styles.container}>
<StatusBar />
{this.state.alertRef && (
<Router
alertRef={this.state.alertRef}
language={this.props.language}
/>
)}
<DropdownAlert ref={ref => (this.alertRef = ref)} />
</View>
);
}
}
Upvotes: 0
Reputation: 138367
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);
}
Upvotes: 1
Reputation: 112827
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>
);
}
}
Upvotes: 1