Reputation: 59
I have a Parent Component which has a Filter Component and the Filter Component has a FilterBox Component with a button on it. Parent > Filter > FilterBox FilterBox has a button which on click calls onButtonPress Function. I want to call this onButtonPress function from Filter Component. Tried using refs also tried binding the function in constructor. Still getting errors.
class Filter extends Component {
constructor() {
super();
this.child = React.createRef();
}
render() {
return (
<View>
<FilterBox
//props
ref = {this.child}
/>
<TouchableOpacity
onPress={()=>this.child.current.onButtonPress()}/>
</View>
)
}
class FilterBox extends Component {
constructor() {
super();
this.onButtonPress = this.onButtonPress.bind(this);
}
onButtonPress = () =>{
console.log("Hi")
}
}
I get a cannot read property 'onButtonPress' of null
Upvotes: 0
Views: 357
Reputation: 66
You can do the following. I reproduce it in react so convert buttons to TouchableOpacity and onPress to onClick.
What it does is pass a function from filter to filterbox as a prop and when you call that function from componentDidMount of filterbox it set the state of filter component and give onButtonPress function to the this.state.propFunc.
class Filter extends Component {
constructor() {
super();
this.child = React.createRef();
this.state = {
propFunc: null
}
this.funcToPass = this.funcToPass.bind(this)
}
funcToPass(fn) {
this.setState({ propFunc: fn })
}
render() {
return (
<div>
<FilterBox
funcToPass={this.funcToPass}
/>
{this.state.propFunc != null && <button onClick={this.state.propFunc} />}
</div>
)
}
}
class FilterBox extends Component {
constructor() {
super();
}
onButtonPress = () => {
console.log("Hi")
}
componentDidMount() {
this.props.funcToPass(this.onButtonPress)
}
render() {
return (
<div>
</div>
)
}
}
Upvotes: 1