Skip to content

Instantly share code, notes, and snippets.

@ashwin1014
Created May 20, 2021 13:43
Show Gist options
  • Save ashwin1014/91bd496c98327aa0b183a25752466f6b to your computer and use it in GitHub Desktop.
Save ashwin1014/91bd496c98327aa0b183a25752466f6b to your computer and use it in GitHub Desktop.
Space component in React Native. (Inspired by Ant Design's "Space" component)
/* eslint-disable react/no-array-index-key */
import React, { memo } from "react";
import { View, StyleSheet } from "react-native";
import PropTypes from "prop-types";
/**
* @param direction -> horizontal, vertical
* @param size -> "xs", "sm", "md", "lg", "xl"
*/
const styles = StyleSheet.create({
flexRow: {
flexDirection: "row"
},
flexCol: {
flexDirection: "column"
},
item: {
alignItems: "center",
justifyContent: "center",
flexDirection: "row"
}
});
const toElementsArray = list => {
if (!list) {
return [];
}
return Array.isArray(list) ? list : [list];
};
const getSpacing = {
xs: 4,
sm: 8,
md: 12,
lg: 16,
xl: 20
};
const Space = ({
direction = "horizontal",
size = "sm",
wrapperStyle = {},
itemStyle = {},
children
}) => {
const childNodes = toElementsArray(children);
const itemsLength = childNodes.length;
const marginDirection =
direction === "horizontal" ? "marginRight" : "marginBottom";
if (itemsLength === 0) {
return null;
}
return (
<View
style={{
...(direction === "horizontal" && styles.flexRow),
...(direction === "vertical" && styles.flexCol),
...wrapperStyle
}}
>
{(childNodes || []).map((child, i) => (
<View
key={i}
style={{
...(childNodes.lastIndexOf(child) === itemsLength - 1
? { [marginDirection]: 0 }
: { [marginDirection]: getSpacing[size] }),
...styles.item,
...itemStyle
}}
>
{child}
</View>
))}
</View>
);
};
Space.propTypes = {
direction: PropTypes.oneOf(["horizontal", "vertical"]),
size: PropTypes.oneOf(["xs", "sm", "md", "lg", "xl"]),
wrapperStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
itemStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
children: PropTypes.element.isRequired
};
export default memo(Space);
@ashwin1014
Copy link
Author

usege:

 import { Text } from "react-native";
 import Space from "./Space";

<Space direction="vertical" size="md">
   <Text>Hello</Text>
   <Text>World</Text>
</Space>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment