Created
May 20, 2021 13:43
-
-
Save ashwin1014/91bd496c98327aa0b183a25752466f6b to your computer and use it in GitHub Desktop.
Space component in React Native. (Inspired by Ant Design's "Space" component)
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
/* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usege: