Skip to content

Instantly share code, notes, and snippets.

@Stringsaeed
Created June 9, 2023 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Stringsaeed/8940abea1d24ccd31197fe8eedd19f10 to your computer and use it in GitHub Desktop.
Save Stringsaeed/8940abea1d24ccd31197fe8eedd19f10 to your computer and use it in GitHub Desktop.
React Native + Typescript
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