Keyboard listener is running more then once

Viewed 968

Hey I'm trying to create an event that will fire when the keyboard shows up but the function is firing more then once, I don't know why ..

import React, { Component } from 'react';
import { Keyboard, Alert, View, TextInput } from 'react-native';

export default class App extends Component {

  constructor(props: any) {
    super(props);
    this.kbDidShowListener = Keyboard.addListener('keyboardDidShow', () => Alert.alert('keyboard is up'));
  }

  componentWillUnmount() {
    this.kbDidShowListener.remove();
  }

  render() {
    return (
      <View style={{ marginTop: 30 }}>
        <TextInput />
      </View>
    );
  }
}

here is an expo for the example (you will see the alert more then once) https://snack.expo.io/H1DHaIdgM

p.s I'm working on Android.

thanks!

1 Answers

The render function does not run only once. Usually refreshes multiple times too, while calculating the state and props. That could explain the issue.

If you want to be sure, try adding a console too inside the render method, to see if the numbers match.

Actually, another thing I am thinking. Try moving the code to the componentWillMount or componentDidMount

componentDidMount(){
    this.kbDidShowListener = Keyboard.addListener('keyboardDidShow', () => Alert.alert('keyboard is up'));
}
Related