Skip to content

Instantly share code, notes, and snippets.

@eai04191
Last active May 31, 2021 08:56
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 eai04191/0e7f841c207fe241610db341b59fec38 to your computer and use it in GitHub Desktop.
Save eai04191/0e7f841c207fe241610db341b59fec38 to your computer and use it in GitHub Desktop.
react native stack and spacer
import React from "react";
import { StyleSheet, View, ViewProps } from "react-native";
interface Props extends ViewProps {
readonly size?: number;
readonly vertical?: boolean;
}
export const Spacer: React.VFC<Props> = ({
size = 0,
vertical = false,
style,
...props
}) => {
return vertical ? (
<View {...props} style={StyleSheet.flatten([style, { minHeight: size }])} />
) : (
<View {...props} style={StyleSheet.flatten([style, { minWidth: size }])} />
);
};
import React from "react";
import { StyleSheet, View, ViewProps } from "react-native";
import { Spacer } from "./Spacer";
interface Props extends ViewProps {
readonly children: React.ReactNode;
readonly spacing?: number;
readonly vertical?: boolean;
}
export const Stack: React.FC<Props> = ({
children,
spacing = 0,
vertical = false,
style,
...props
}) => {
const items = Array.isArray(children) ? children : [children];
const itemsWithSpacer = items.map((item, index) => (
<React.Fragment key={index}>
{item}
{index < items.length - 1 && (
<Spacer size={spacing} vertical={vertical} />
)}
</React.Fragment>
));
return (
<View
{...props}
style={StyleSheet.flatten([
style,
{ display: "flex", flexDirection: vertical ? "column" : "row" },
])}
>
{itemsWithSpacer}
</View>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment