Arpith Siromoney 💬

Handling Keyboard Events in React Native

I’m building an app called Constellational to share notes (sign up here!) and a big part of this is a full screen, distraction-free Text Input.

I was using an NPM package called React Native Keyboard Events to do this, but it looks like that is no longer necessary.

{ DeviceEventEmitter } = React;
class EditPage extends React.Component {
 constructor(props, context) {
   super(props, context);
   this.updateKeyboardSpace = (deviceEvent) => {
     var change = deviceEvent.endCoordinates.height;
     this.setState({
       height: this.state.height - change,
       isKeyboardUp: true
     });
   };
   this.resetKeyboardSpace = () => this.setState({
     height: this.state.fullHeight,
     isKeyboardUp: false
   });
 }
  componentDidMount() {
   DeviceEventEmitter.addListener('keyboardWillShow', this.updateKeyboardSpace);
   DeviceEventEmitter.addListener('keyboardWillHide', this.resetKeyboardSpace);
 }
 
 render() {
   return (
     <View style={styles.page} onLayout={(ev) => {
       // 80 is for the navbar on top
       var fullHeight = ev.nativeEvent.layout.height - 80;
       this.setState({height: fullHeight, fullHeight: fullHeight});
     }}>
       <NavBar leftButton={this.cancelButton} title={title} rightButton={this.postButton}/>
       <ScrollView keyboardDismissMode='interactive'>
         <TextInput
           multiline={true}
           onChangeText={(text) => {
             this.state.post.data = text;
           }}
           defaultValue={this.state.post.data}
           autoFocus={true}
           style={[styles.input, {height:this.state.height}]}
         />
       </ScrollView>
     </View>
   );
 }
}

What’s going on here: when the component mounts, a listener is added to the ‘keyboardWillShow’ (and hide) event. This listener adjusts the height of the TextInput to match the size of the visible screen (that’s the height of the screen minus the height of the keyboard). That’s about it!

Bonus: should I use Dimensions.get(‘window’).height?