Created
June 9, 2023 00:28
-
-
Save Stringsaeed/8940abea1d24ccd31197fe8eedd19f10 to your computer and use it in GitHub Desktop.
React Native + Typescript
This file contains hidden or 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, { useMemo } from "react"; | |
import { | |
ScrollView, | |
ScrollViewProps, | |
StyleSheet, | |
View, | |
ViewProps, | |
} from "react-native"; | |
type BaseProps<T> = T extends "scroll" | |
? ScrollViewProps | |
: T extends "fixed" | |
? ViewProps | |
: never; | |
type Props<T extends "scroll" | "fixed"> = BaseProps<T> & { | |
type: T; | |
centered?: boolean; | |
}; | |
function FixedScreen({ | |
centered, | |
style: overrideStyle, | |
...restProps | |
}: Props<"fixed">) { | |
const containerStyle = useMemo( | |
() => | |
StyleSheet.flatten([ | |
styles.flex, | |
styles.background, | |
styles.beautifulPadding, | |
centered && styles.centered, | |
overrideStyle, | |
]), | |
[centered, overrideStyle] | |
); | |
return <View {...restProps} style={containerStyle} />; | |
} | |
function ScrollScreen({ | |
centered, | |
contentContainerStyle: overrideContentStyle, | |
style: overrideStyle, | |
...restProps | |
}: Props<"scroll">) { | |
const containerStyle = useMemo( | |
() => StyleSheet.flatten([styles.flex, styles.background, overrideStyle]), | |
[overrideStyle] | |
); | |
const contentContainerStyle = useMemo( | |
() => | |
StyleSheet.flatten([ | |
styles.beautifulPadding, | |
centered && styles.centered, | |
centered && styles.grow, | |
overrideContentStyle, | |
]), | |
[centered, overrideContentStyle] | |
); | |
return ( | |
<ScrollView | |
{...restProps} | |
style={containerStyle} | |
contentContainerStyle={contentContainerStyle} | |
/> | |
); | |
} | |
export default function ScreenContainer<T extends "scroll" | "fixed">({ | |
type, | |
...restProps | |
}: Props<T>) { | |
if (type === "fixed") { | |
return <FixedScreen type={type} {...restProps} />; | |
} | |
if (type === "scroll") { | |
return <ScrollScreen type={type} {...restProps} />; | |
} | |
return null; | |
} | |
const styles = StyleSheet.create({ | |
flex: { | |
flex: 1, | |
}, | |
centered: { | |
justifyContent: "center", | |
alignItems: "center", | |
}, | |
background: { | |
backgroundColor: "white", | |
}, | |
beautifulPadding: { | |
paddingHorizontal: 16, | |
}, | |
grow: { | |
flexGrow: 1, | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment