I have a parent functional component in my react-native app, and a child class component. I want to call a method of child in my parent component. I try to pass a ref to child and use it to call my method in parent.
my parent component:
const Screen = ({...props}) => {
// ...
let cats;
const onHeadSearchPress = () => {
console.log('check', cats); // log undefined
cats.toggleCategoryList();
cats.renderSearch();
};
retrun (
// ...
<Categories onRef={ref => (cats = ref)} />
// ...
)
}
my child component:
class Component extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
//..
};
toggleCategoryList() {
if (this.state.showList === false) {
Animated.timing(this.animateChevronY, {
toValue: 1,
duration: 300,
useNativeDriver: true,
easing: Easing.linear,
}).start();
}
if (this.state.showList === true) {
Animated.timing(this.animateChevronY, {
toValue: 0,
duration: 300,
useNativeDriver: true,
easing: Easing.linear,
}).start();
}
setTimeout(() => {
this.setState({
showList: !this.state.showList,
});
}, 100);
}
renderSearch() {
this.setState({
showSearch: true,
});
Animated.timing(this.searchBoxFade, {
toValue: 1,
duration: 200,
easing: Easing.linear,
}).start();
}
componentDidMount() {
console.log('checkthis', this); // log correctly
this.props.onRef(this);
}
render() {
// ...
}
}
But log in parent make undefined and methods not running and make error "Cannot read property of undefined (reading toggleCategoryList)"
If I understand, you don't need a onRef event. You can use ref. And if your app is crashing with first render, there should be a null check.
if(cats){
cats.toggleCategoryList?.();
cats.renderSearch?.();
}