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

Viewed 1163

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.

1 Answers

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>
    );
Related