Kyle Banks

Why React Native Modals Require an onRequestClose Callback Property on Android

Written by @kylewbanks on Nov 12, 2016.

I haven’t spent a whole lot of time with React Native, mostly using it for prototyping or for quick tools I personally need. One common thing I seem to require though is a Modal component, and I was always thinking how strange it is that the Modal requires an onRequestClose callback on Android devices.

It’s not strange to have required properties by any means, but the fact that this one property is Android only is particularly unique from what I can tell. The documentation simply states:

The onRequestClose prop allows passing a function that will be called once the modal has been dismissed.
On the Android platform, this is a required function.

There’s no real explanation for this requirement, and simply passing an empty function satisfies the requirement just fine. However it recently occurred to me after using the Modal a few times and implementing the BackAndroid event myself to handle closing the Modal, that Android devices commonly have hardware buttons and iOS devices do not - perhaps this is the reason for that strange callback requirement?

Sure enough, a quick test validates this:

// render()
<Modal 
    visible={this.state.modalVisible}
    onRequestClose={_closeModal.bind(this)} />

// Elsewhere...
_closeModal() {
    setState({
        modalVisible: false
    });
}

Hit the hardware back button when the Modal is visible and sure enough, the Modal now closes properly without custom BackAndroid logic.

I’m not entirely sure if this is the only time that onRequestClose is executed, and if it ever is on iOS, but this seems to be the only reason I can find for why this is necessary on Android, and from what I can tell with a quick peak at the source code it looks this is only ever called from Android. I assume this means on iOS you’d be unable to rely on this as a close event callback like the documentation seems to state.

Coincidentally while writing this post I was going to submit a pull request to update the documentation, but someone beat me to it by about twelve hours.

Let me know if this post was helpful on Twitter @kylewbanks or down below!