I have a list of countries in a flatlist with a search filter I made using an API. I want to make it so when I press on a country's name in the flatlist, it takes me to a screen where it prints out that specific country's name and it its number of cases. LocationDataScreen
is the screen I want to print out that info. Any help is appreciated :)
This is my current code below:
const fetchData = () => {
const apiURL = "https://coronavirus-19-api.herokuapp.com/countries";
fetch(apiURL)
.then((response) => response.json())
.then((responseJson) => {
setFilteredData(responseJson);
setMasterData(responseJson);
})
.catch((error) => {
console.error(error);
});
};
const SearchFilter = (text) => {
if (text) {
const newData = filteredData.filter((item) => {
const itemData = item.country;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setFilteredData(newData);
setSearch(text);
} else {
setFilteredData(masterData);
setSearch(text);
}
};
const ItemView = ({ item }) => {
return (
<RectButton
onPress={() => navigation.navigate("LocationDataScreen")}
style={styles.searchcontainer}
>
<Text style={[styles.itemStyle, { textTransform: "capitalize" }]}>
{item.id}
{item.country.toUpperCase()}
</Text>
</RectButton>
);
};
const ItemSeparatorView = () => {
return (
<View
style={{
height: 1.5,
width: "90%",
marginLeft: 35,
backgroundColor: "#f3f2f8",
}}
/>
);
};
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
stickyHeaderIndices={[0]}
style={[styles.container, { flex: 1 }]}
>
<SearchBarCustom
value={search}
placeholder="Search"
containerStyle={{ backgroundColor: "#f3f2f8" }}
inputContainerStyle={{
backgroundColor: "#e3e3e9",
height: 25,
marginHorizontal: 5,
marginTop: -5,
}}
placeholderTextColor="#96969b"
platform="ios"
onChangeText={(text) => SearchFilter(text)}
/>
<FlatList
data={filteredData}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={ItemSeparatorView}
renderItem={ItemView}
style={styles.listcontainer}
/>
</ScrollView>
);
};
Check out a Snack that I created for you. It has the implementation.
Your
ItemView
function should look like thisYour
LocationDataScreen.js
screen should look like thisFor
Custom Header Title
asitem.country
we can do thisIn you
ItemView
function youronPress
should look like thisYour
Stack.Screen
part for second screen should look like thisNow when you click on the country you'll see its name on the top as Header title.
Check my Snack to see working example.