'Styling conditional FlatList?
I want to show FlatList only if there are results from an axios call. Unfortunately when there are some results, they are showing beneath the components below it, like TextArea, etc. I tried a lot of styling combinations but nothing works. Any help is appriciated!
const CreateScreen = () => {
const [searchKeyword, setSearchKeyword] = useState("");
const [searchResults, setSearchResults] = useState("");
const [isShowingResults, setIsShowingResults] = useState(false);
searchLocation = async (text) => {
setSearchKeyword(text);
axios
.request({
method: "post",
url:
"https://maps.googleapis.com/maps/api/place/autocomplete/json?key=" +
apiKey +
"&input=" +
searchKeyword +
"&types=(cities)&components=country:bg&language=bg",
})
.then((response) => {
console.log(response.data);
setSearchResults(response.data.predictions);
setIsShowingResults(true);
})
.catch((e) => {
console.log(e.response);
});
};
return (
<ScrollView>
<Text style={{ marginBottom: 3 }}>Address</Text>
<View style={styles.autocompleteContainer}>
<TextInput
returnKeyType="search"
placeholderTextColor="#000"
onChangeText={(text) => searchLocation(text)}
value={searchKeyword}
/>
{isShowingResults && (
<FlatList
data={searchResults}
renderItem={({ item, index }) => {
return (
<TouchableOpacity
style={styles.resultItem}
onPress={() => {
setSearchKeyword(item.description);
setIsShowingResults(false);
}}
>
<Text>{item.description}</Text>
</TouchableOpacity>
);
}}
keyExtractor={(item) => item.id}
style={styles.searchResultsContainer}
/>
)}
</View>
<Text style={{ marginBottom: 3 }}>Title</Text>
<TextInput />
</ScrollView>
);
}
const styles = StyleSheet.create({
autocompleteContainer: {
zIndex: 1,
},
searchResultsContainer: {
width: "100%",
backgroundColor: "#fff",
position: "absolute",
top: 50,
},
resultItem: {
justifyContent: "center",
height: 40,
borderBottomColor: "#ccc",
borderBottomWidth: 1,
paddingLeft: 15,
},
});
Solution 1:[1]
{isShowingResults? (
<FlatList
data={searchResults}
renderItem={({ item, index }) => {
return (
<TouchableOpacity
style={styles.resultItem}
onPress={() => {
setSearchKeyword(item.description);
setIsShowingResults(false);
}}
>
<Text>{item.description}</Text>
</TouchableOpacity>
);
}}
keyExtractor={(item) => item.id}
style={styles.searchResultsContainer}
/>
):null}
You can try this, or you can just pass ListEmptyComponent to null, nothing will display when you have empty array in data of flatlist
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alok Singh |
