Christopher Duke Christopher Duke - 2 months ago 8
React JSX Question

How do I bind to a function that has been passed in to a child component via a prop so that I can call it in a function in the child component

In the code below, can someone advise on how access the function stored in the

closeModal
prop that is passed in to the child
QRScan
component?

I've tried
this.props.closeModal.bind(this)
in the constructor of
QRScan
but when I call
this.props.closeModal()
in the
_onBarCodeRead
function I get an
undefined is not an object (evaluating 'this.props.closedModal')
error.

The props are definitely getting passed in to the constructor, I just can't seem to bind the function correctly. Any help much appreciated!

class Test extends React.Component {

constructor(props) {
super(props);
}

_test(){
console.log("test worked")
}

render() {
return (
<View>
<QRScan closeModal={this._test}/>
</View>
}
}


Child class:

class QRScan extends React.Component {

constructor(props)
{
super(props)
console.log(this.props)
this.props.closeModal.bind(this);
}

render() {
return (
<BarcodeScanner
onBarCodeRead={this._onBarCodeRead}
width={windowWidth}
height={windowWidth * cameraAspectRatio}
style={styles.camera}>
<View style={styles.rectangleContainer}>
<View style={styles.rectangle} />
</View>
</BarcodeScanner>
);
}
_onBarCodeRead(e) {
console.log(e);
Vibration.vibrate();
this.props.closeModal();
}
}

Answer

The problem is actually the this._onBarCodeRead is not bound correctly.

In the child component's constructor you need to add following this._onBarCodeRead = this._onBarCodeRead.bind(this);