Skip to content

Instantly share code, notes, and snippets.

@benvium
Last active October 15, 2020 04:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benvium/d5f7a520289f7d47296d to your computer and use it in GitHub Desktop.
Save benvium/d5f7a520289f7d47296d to your computer and use it in GitHub Desktop.
React Native. Resize a view when the keyboard appears or hides.
'use strict';
const React = require('react-native');
const {
DeviceEventEmitter,
LayoutAnimation,
Dimensions,
} = React;
// only used to get the height of the navbar..
const { Size, } = require('../theme/theme.js');
/**
* Mixin to simplify resizing a page in an NavigatorIOS when the keyboard appears/disappears.
*
* IMPORTANT: this Mixin depends on Subscribable.Mixin.
*
* ```
* const Subscribable = require('Subscribable');
* const KeyboardResizeMixin = require('../mixins/KeyboardResizeMixin.js');
*
* mixins: [
* ....
* Subscribable.Mixin,
* KeyboardResizeMixin,
* ],
* render() {
* return (<View style={{height: this.getVisibleHeight()}}></View>);
* }
* ...
* ```
*/
const KeyboardResizeMixin = {
getInitialState() {
console.log(`KeyboardResizeMixin.getInitialState ${this.constructor.displayName}`);
return {
visibleHeight: Dimensions.get('window').height - Size.navAndStatusBar,
}
},
componentWillMount() {
console.log(`KeyboardResizeMixin.componentWillMount ${this.constructor.displayName}`);
//Use mixin so the listener is removed again
this.addListenerOn(DeviceEventEmitter, 'keyboardWillShow', this._keyboardWillShow, this);
this.addListenerOn(DeviceEventEmitter, 'keyboardWillHide', this._keyboardWillHide, this);
},
/**
* Use this in your render() method to set the height of the outermost element.
*
* Then, the outermost element will be resized when the keyboard shows/hides
*
* @returns height of page when shown in a NavigatorIOS, taking into account the keyboard
*/
getVisibleHeight() {
return this.state.visibleHeight;
},
_keyboardWillShow (e) {
console.log(`KeyboardResizeMixin._keyboardWillShow ${this.constructor.displayName}`);
let newSize = Dimensions.get('window').height - e.endCoordinates.height - Size.navAndStatusBar;
// Animate the update
LayoutAnimation.spring();
this.setState({visibleHeight: newSize});
},
_keyboardWillHide (e) {
console.log(`KeyboardResizeMixin._keyboardWillHide ${this.constructor.displayName}`);
// Animate the update
LayoutAnimation.spring();
this.setState({visibleHeight: Dimensions.get('window').height - Size.navAndStatusBar});
}
};
module.exports = KeyboardResizeMixin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment