I have a grid of pokemons (below).
I am using flatlist to render the pokemons using the data fetched from an api. When I click on a pokemon I want to display the next page (below)
//Function for FlatList - To render Pokemon images
const renderPokemon = ({ item }) => {
let url = item.url
const idPokemon = url.split('https://pokeapi.co/api/v2/pokemon/')
const link = urlImage + idPokemon[1].substring(0, idPokemon[1].length-1) + ".png"
return (
//Individual images
<View style={styles.pokemons}>
<Image
style={styles.image}
resizeMode='contain'
source={{uri:link}}
/>
<Text style={styles.text}>{item.name}</Text>
</View>
)
}
//App container
<NavigationContainer>
<View style={styles.container}>
<TopBar/>
{/**Pokemon image grid display*/}
<FlatList
numColumns={2}
data={pokemons}
renderItem={renderPokemon}
keyExtractor={pokemon => `key-${pokemon.name}`}
style={styles.container}
onPress={() => alert('clicked')} //WHERE DO I PUT THIS ?
>
</FlatList>
</View>
<NavigationContainer>
But it doesnt seem to be responding. I am using Alert just to test. How to I get the flatlist imaages to handlle onpress so it navigates to the next page and displays the data for that specific pokemon?
Thanks in advance!
You need to add Pressable inside each rendered item, after importing from react-native and add onPress event and do as required in the callback function.(like in your case, navigate to new screen). You can pass pokemonDetailsObj in route params or just the pokemonId, depending on how the Pokemon details Component works.
I would also suggest you to create stack navigator and register your screen components to better use [reactnavigation][1] features.
import { Pressable} from 'react-native';
const renderPokemon = ({ item }) => {
let url = item.url
const idPokemon = url.split('https://pokeapi.co/api/v2/pokemon/')
const link = urlImage + idPokemon[1].substring(0, idPokemon[1].length-1) + ".png"
return (
//Individual images
<Pressable
onPress={() => {
// pass the 'ScreenName' of the Pokemon details component.
props.navigation.navigate('ScreenName', {
// props to be passed to the component like pokemonId or full pokemon Details Obj
})
}}
>
<Image
style={styles.image}
resizeMode='contain'
source={{uri:link}}
/>
<Text style={styles.text}>{item.name}</Text>
</Pressable>
)
}
[1]: https://reactnavigation.org/docs/getting-started