Hide keyboard and lose focus when user click outside the react-native-paper searchbar input
Asked Answered
A

2

5

I use react-native-paper searchbar component to implement a search component. Following is the basic code I developed. But when I click outside the search input field, the keyboard does not collapse and onFocus is not removed from the input.

import * as React from 'react';
import { Searchbar } from 'react-native-paper';

const SearchBar = () => {
  const [searchQuery, setSearchQuery] = React.useState('');

  const onChangeSearch = query => setSearchQuery(query);
  cons onClick = () => { console.log(`searching for ${query}`);};

  return (
    <Searchbar
      placeholder="Search"
      onChangeText={onChangeSearch}
      value={searchQuery}
      onIconPress={onClick}
    />
  );
};

export default SearchBar;

Can somebody please let me know how to hide the keyboard when user click outside the search input? Thanks.

Apothecium answered 16/5, 2022 at 16:20 Comment(0)
E
8

You could wrap everything in a TouchableWithoutFeedback and dismiss the keyboard manually (which will also make it loose the focus).

Here is a minimal working example.

import React from 'react';
import { TouchableWithoutFeedback, Keyboard } from 'react-native';
import { Searchbar } from 'react-native-paper';

...

    return (
      <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        <View style={{flex: 1, paddingTop: 100}}>
            <Searchbar
            placeholder="Search"
            onChangeText={onChangeSearch}
            value={searchQuery}
            onIconPress={onClick}
          />
        </View>
      </TouchableWithoutFeedback>
    );
Euphony answered 16/5, 2022 at 21:18 Comment(0)
P
1

You can use the following wrapper component. This one works pretty well for me.

import { KeyboardAvoidingView, ScrollView } from "react-native";

const KeyboardDismissibleView = ({ backgroundColor = "#F5F4FF", children }) => {
    return <KeyboardAvoidingView behavior="height" style={{ flex: 1, paddingHorizontal: 10, backgroundColor }}>
        <ScrollView showsVerticalScrollIndicator={false} style={{ flex: 1 }} keyboardDismissMode="interactive">
            {children}
        </ScrollView>
    </KeyboardAvoidingView>
}

export default KeyboardDismissibleView;
Procephalic answered 11/11, 2022 at 5:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.