Search code examples
react-nativetextinput

How to make the Keyboard show when touching the parent view


I'm creating an app with React Native & Expo. One of the search inputs includes an icon, so I did it like so:

        <View style={styles.inputContainer}>
            <FontAwesome name="search" size={20} color="black" />
            <TextInput
                style={styles.input}
                value={search}
                placeholder="Pesquise"
                placeholderTextColor={text_gray}
                onChangeText={(text) => setSearch(text)}
            />
        </View>

But the Keyboard shows only when I click the TextInput, and I need to open it wherever I click the View that wraps it and the icon. How can I achieve that?


Solution

  • Create a ref to the TextInput and then call REF.current.focus() to focus on the textInput and REF.current.blur() to blur it. Use Pressable instead of View, its just like a View but with different onPress events.

    const textInput = useRef(null);
    
    return (
      <Pressable style={styles.inputContainer} onPress={() => textInput?.current?.focus()}>
        <FontAwesome name="search" size={20} color="black" />
        <TextInput
          ref={textInput}
          style={styles.input}
          value={search}
          placeholder="Pesquise"
          placeholderTextColor={text_gray}
          onChangeText={(text) => setSearch(text)}
        />
      </Pressable>
    )