Last active
September 16, 2020 14:10
-
-
Save thibaut-d/6484735aae493901193efc8a2f8b3a89 to your computer and use it in GitHub Desktop.
React Navigator's StackNavigator and a screen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState, useContext, FC } from 'react' | |
import { StyleSheet, SafeAreaView, FlatList } from 'react-native' | |
import { StackNavigationProp } from '@react-navigation/stack' | |
import { RouteProp } from '@react-navigation/native' | |
import { HomeScreenStackParamList } from '../navigation/navigationTypes' | |
interface Props { | |
navigation: StackNavigationProp<ScreenNameStackParamList, 'Home'> | |
route: RouteProp<ScreenNameStackParamList, 'Home'> | |
} | |
/** | |
* Screen component description | |
* | |
* @returns Screen | |
*/ | |
const HomeScreen: FC<Props> = ({ route, navigation }) => { | |
// From the previous screen | |
const initialData = route?.params?.data | |
// Context | |
const { fromContext } = useContext(ContextName) | |
// Custom hooks | |
const { output } = useCustomHook() | |
// Internal state | |
const [data, setData] = useState<DataType>(initialData) | |
useEffect(() => { | |
let mounted = true | |
// Declaration | |
const init = async (): Promise<void> => { | |
const result = await getResult(fromContext) | |
// protect delayed effects that could happen after that the component un-mount | |
if (mounted) setData(result) | |
} | |
// Execution | |
init(fromContext) | |
// cleanup | |
return (): void => { | |
mounted = false | |
} | |
}, [fromContext]) | |
// Component JSX | |
return ( | |
<SafeAreaView style={styles.container}> | |
<FlatList | |
style={styles.inContainer} | |
data={data} | |
renderItem={(item): JSX.Element => <RenderItem item={item} />} | |
keyExtractor={(item): string => item.id} | |
/> | |
</SafeAreaView> | |
) | |
} | |
/// Styles /// | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, // full space | |
flexDirection: 'row', // elements disposition | |
justifyContent: 'center', // following flexDirection | |
alignItems: 'center', // perpendicular to flexDirection | |
}, | |
inContainer: { | |
alignSelf: 'center', // following flex direction | |
}, | |
}) | |
export default HomeScreen |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment