FIX: children of FContainer could be null

This commit is contained in:
Ivan Vershigora 2020-09-21 13:16:09 +03:00
parent cf0d35764a
commit 38520fd656

View File

@ -27,30 +27,32 @@ const cStyles = StyleSheet.create({
export const FContainer = ({ children }) => { export const FContainer = ({ children }) => {
const [newWidth, setNewWidth] = useState(); const [newWidth, setNewWidth] = useState();
const flag = useRef(false); const layoutCalculated = useRef(false);
const onLayout = event => { const onLayout = event => {
if (flag.current) return; if (layoutCalculated.current) return;
const { width } = event.nativeEvent.layout; const { width } = event.nativeEvent.layout;
const maxWidth = Dimensions.get('window').width - BORDER_RADIUS - 10; const maxWidth = Dimensions.get('window').width - BORDER_RADIUS - 10;
const len = React.Children.count(children); const len = React.Children.toArray(children).filter(Boolean).length;
let newWidth = width * len > maxWidth ? Math.floor(maxWidth / len) : Math.ceil(width + ICON_MARGIN); let newWidth = width * len > maxWidth ? Math.floor(maxWidth / len) : Math.ceil(width + ICON_MARGIN);
if (len === 1 && newWidth < 90) newWidth = 90; // to add Paddings for lonely small button, like Scan on main screen if (len === 1 && newWidth < 90) newWidth = 90; // to add Paddings for lonely small button, like Scan on main screen
setNewWidth(newWidth); setNewWidth(newWidth);
flag.current = true; layoutCalculated.current = true;
}; };
return ( return (
<View onLayout={onLayout} style={[cStyles.root, newWidth ? cStyles.rootPost : cStyles.rootPre]}> <View onLayout={onLayout} style={[cStyles.root, newWidth ? cStyles.rootPost : cStyles.rootPre]}>
{newWidth {newWidth
? React.Children.map(children, (c, index) => ? React.Children.toArray(children)
React.cloneElement(c, { .filter(Boolean)
width: newWidth, .map((c, index, array) =>
key: index, React.cloneElement(c, {
first: index === 0, width: newWidth,
last: index === React.Children.count(children) - 1, key: index,
}), first: index === 0,
) last: index === array.length - 1,
}),
)
: children} : children}
</View> </View>
); );