I'm new to react-native
and I am running into some issues that I am not sure how to tackle.
I have components that get dynamically rendered based of some API
data.
for (var i = 0; i < data.length; i++)
{
categoryComponents.push(
<Card key={data[i].id}>
<CardItem>
<Body>
<TouchableHighlight onPress={(event) => {
const { navigate } = this.props.navigation;
navigate('Category', { category: data[i].id });
}}>
<Text>{data[i].name + " " + data[i].id}</Text>
</TouchableHighlight>
</Body>
</CardItem>
</Card>
);
}
As you can see, I store dynamic components inside an array. Which I render to the screen:
render() {
return (
<Container>
<Content style={styles.spacer}>{categoryComponents}</Content>
</Container>
)
}
The issue is that inside my TouchableHighlight
component, the onPress
event doesn't seem to accept the data[i].id
variable. It throws an error saying undefined
. However, I use it outside the onPress
event and it is defined.
I was trying to fix this issue so I changed my code:
for (var i = 0; i < data.length; i++)
{
var name = data[i].name;
var id = data[i].id;
categoryComponents.push(
<Card key={id}>
<CardItem>
<Body>
<TouchableHighlight onPress={(event) => {
const { navigate } = this.props.navigation;
navigate('Category', { category: id });
}}>
<Text>{name + " " + id}</Text>
</TouchableHighlight>
</Body>
</CardItem>
</Card>
);
}
As you can see, I simply store the values I will use into local variables and reference those variables instead of the data
.
This did not fix the issue, but gave me more insight.
Now my TouchableHighlight
components onPress
event does accept the variable, but it only uses the last iteration of the loop assignment.
So my id
variable is always assigned to 9 across all components inside the TouchableHighlight
. Even though outside onPress
event the id
variable is changing.
Due to this issue, none of my links are dynamic. How can I have dynamic onPress
events on a TouchableHighlight
component?
EDIT: I use native-base
for the components.