import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { View, Text, FlatList, TouchableOpacity, Button } from 'react-native';
const Stack = createNativeStackNavigator();
function UserListScreen({ navigation }) {
const users = [
{ id: '1', name: 'Alice', age: 25 },
{ id: '2', name: 'Bob', age: 30 },
{ id: '3', name: 'Carol', age: 22 },
];
return (
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ fontSize: 24, marginBottom: 20 }}>User List</Text>
<FlatList
data={users}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<TouchableOpacity
onPress={() => navigation.navigate('UserDetail', { name: item.name, age: item.age })}
style={{ paddingVertical: 10 }}
accessibilityRole="button"
accessibilityLabel={`View details for ${item.name}`}
>
<Text style={{ fontSize: 18 }}>{item.name}</Text>
</TouchableOpacity>
)}
/>
</View>
);
}
function UserDetailScreen({ route, navigation }) {
const { name, age } = route.params;
return (
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ fontSize: 24, marginBottom: 20 }}>User Detail</Text>
<Text style={{ fontSize: 18, marginBottom: 10 }}>Name: {name}</Text>
<Text style={{ fontSize: 18, marginBottom: 20 }}>Age: {age}</Text>
<Button title="Back" onPress={() => navigation.goBack()} accessibilityLabel="Go back to user list" />
</View>
);
}
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="UserList" component={UserListScreen} />
<Stack.Screen name="UserDetail" component={UserDetailScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
We created two screens: UserListScreen and UserDetailScreen. The UserListScreen shows a list of users using FlatList. Each user name is wrapped in a TouchableOpacity so it can be tapped. When tapped, it navigates to the UserDetailScreen and passes the user's name and age as parameters.
In UserDetailScreen, we get the parameters from route.params and display them in Text components. We also added a Back button that calls navigation.goBack() to return to the list.
This shows how to pass data between screens in React Native using React Navigation.