I am using searchable drop-down using the below module.
https://www.npmjs.com/package/react-native-searchable-dropdown
When the drop-down is open, when I click on back button the drop-down does not close. And until I select any option it will be opened only. How to resolve this?
<View style={{ marginTop: 5 }}>
<SearchableDropdown
onItemSelect={(item, index) => {
setItemname(item.value);
setItemIndex(index);
}}
itemStyle={{
padding: 10,
marginTop: 2,
backgroundColor: '#ddd',
borderColor: '#bbb',
borderWidth: 1,
borderRadius: 5,
}}
itemTextStyle={{ color: '#222' }}
itemsContainerStyle={{ maxHeight: 140 }}
items={items}
defaultIndex={itemindex}
resetValue={false}
textInputProps={
{
placeholder: "Select Item",
underlineColorAndroid: "transparent",
style: {
padding: 12,
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 5,
},
}
}
listProps={{
nestedScrollEnabled: true,
}}
/>
</View>
The SearchableDropDown
component uses TextInput
's onBlur
prop to set its focus
state to false
on blur (code reference).
When the focus
state is true
the FlatList
is rendered that contains the items (code reference).
The problem is that when you press the back button onBlur
is not triggered, meaning the focus
state is not set to false
and the FlatList
with the items is still rendered.
You could conditionally hide the flatlist based on whether the keyboard is hidden or not.
import React, { Component, useState, useEffect, useRef } from "react";
import { View, TextInput, Keyboard } from "react-native";
import SearchableDropdown from "react-native-searchable-dropdown";
const App = () => {
const [itemname, setItemname] = useState("");
const [itemindex, setItemIndex] = useState(0);
const [isKeyboardVisible, setKeyboardVisible] = useState(false);
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener(
"keyboardDidShow",
() => {
setKeyboardVisible(true);
}
);
const keyboardDidHideListener = Keyboard.addListener(
"keyboardDidHide",
() => {
setKeyboardVisible(false);
}
);
return () => {
keyboardDidHideListener.remove();
keyboardDidShowListener.remove();
};
}, []);
return (
<View style={{ marginTop: 5 }}>
<SearchableDropdown
onItemSelect={(item, index) => {
setItemname(item.value);
setItemIndex(index);
}}
itemStyle={{
padding: 10,
marginTop: 2,
backgroundColor: "#ddd",
borderColor: "#bbb",
borderWidth: 1,
borderRadius: 5,
}}
itemTextStyle={{ color: "#222" }}
itemsContainerStyle={
isKeyboardVisible ? { maxHeight: 140 } : { display: "none" }
}
items={items}
defaultIndex={itemindex}
resetValue={false}
textInputProps={{
placeholder: "Select Item",
underlineColorAndroid: "transparent",
style: {
padding: 12,
borderWidth: 1,
borderColor: "#ccc",
borderRadius: 5,
},
}}
listProps={{
nestedScrollEnabled: true,
}}
/>
</View>
);
};
export default App;
The implementation above sets itemsContainerStyle
to an object with display
set to 'none'
when the isKeyboardVisible
state is false
.