React Children only expected to receive a single react child when using with TouchableWithoutFeedback

142 views Asked by At

In my application I have a text input, I want to hide the keyboard and lose focus whenever the user clicks anywhere on the screen or closes the keyboard.

I created this function for this:

interface DismissKeyBoardProps {
  children?: ReactNode
} 

const DismissKeyboard: React.FC<DismissKeyBoardProps> = ({ children }) => (
  <TouchableWithoutFeedback 
  onPress={() => Keyboard.dismiss()}> {children}
  </TouchableWithoutFeedback>
);

I use the above method like that:

const App: React.FC = () => {

  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <Text> Test </Text>
        <DismissKeyboard>
          <TextInput placeHolder= {"place holder"}/>
        </DismissKeyboard>
      </SafeAreaView>
    </>
  );
}; 

However, when I try to run it I get an error: React.children.only expected to receive a single React element child.

I don't understand why am I getting this error, when DismissKeyBooard has indeed only one child - TextInput.

Edit: I tried the suggested solution like that, but I keep getting the same error.

  return (
    <View>
      <SafeAreaView>
        <>
          <DismissKeyboard>
            <TextInput style={{height: 40, borderColor: 'gray', borderWidth: 1}} placeHolder={"hint"}/>
          </DismissKeyboard>
        </>
      </SafeAreaView>
    </View>
  );
1

There are 1 answers

0
Batraz Jioty On

Try to wrap your children with <View>, I guess it will help you.

const DismissKeyboard: React.FC<DismissKeyBoardProps> = ({ children }) => (
  <TouchableWithoutFeedback 
  onPress={() => Keyboard.dismiss()}> 
   <View>
    {children}
   </View>
  </TouchableWithoutFeedback>
);