javascriptreact-nativehigh-order-component

Dismiss keyboard with TouchableWithoutFeedback - HighOrderComponent


I am trying to make a High Order Component that is supposed to wrap a component with TouchableWithoutFeedback in order to hide the keyboard whenever the user presses outside the keyboard.

My high order component looks like this:

const DismissKeyboardHOC = Comp => {
  return props => (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
      <Comp {...props} />
    </TouchableWithoutFeedback>
  );
};
export default DismissKeyboardHOC;

In my LoginScreen I have wrapped it with my HOC:

export default DismissKeyboardHOC(LoginScreen);

The potential problem I am facing is that when I look at the inspector the TouchableWithoutFeedback ends up wrapping around my LoginScreen instead of wrapping around SafeAreaView(where it is supposed to be).

I have tried to manually put the TouchableWithoutFeedback in the LoginScreen and it works flawlessly but i doesnt work in my HOC.


Solution

  • 1) change child of TouchableWithoutFeedback to :

      <Comp style={{flex: 1}} {...props}>
        {children}
      </Comp>
    

    2) change your export to :

    export const DismissKeyboard = DismissKeyboardHOC(View);
    

    NOTE: Import view from react native like this:

    import {view} from 'react-native'
    

    3) wrap your views in LoginScreen component with DismissKeyboard like this:

    return(
    <DismissKeyboard>
    // All the children
    </DissmissKeyboard>
    )