Manish Kumar
Manish Kumar

Reputation: 566

How to give spacing between the content of view in react native?

I am new in react native,I have to view right and left container given flex-between them, now I have to give space in contents of left and right container also.

image shown in the below diagram as well as styling code,

  const styles = StyleSheet.create({
  mainContainer: {
    width: "100%",
    flexDirection: "row",
    height: moderateScale(90),
    backgroundColor: "red",
    justifyContent: "space-between",
  },
  containerLeft: {
    flexDirection: "row",
    top: moderateScale(40),
    backgroundColor: "green",
    margin: moderateScale(12),
  },
  containerRightIcons: {
    flexDirection: "row",
    justifyContent: "flex-end",
    top: moderateScale(40),
    margin: moderateScale(12),
    backgroundColor: "blue",
  },
});

enter image description here

Upvotes: 1

Views: 1490

Answers (1)

David Scholz
David Scholz

Reputation: 9806

Wrap the individual child components inside a View and provide a marginRight when necessary. We could create a new component that handles this behaviour.

export function Spacer({isHorizontal = true, space = 10, children}) {
    return <View style={isHorizontal ? {flexDirection: "row"} : null}>
        { 
            React.Children.map(children, (child, index) => {
                return index < children.length - 1 ? <View style={{marginRight: space}}>{child}</View> : child
            })
        }
    </View>
}

We use the isHorizontal flag to indicate whether the children are layed out in a row. The default value is set to true to satisfy your current design. However, we can reuse it for column based layouts as well. The default spacing is set to 10. We can control it using the space prop.

Then, use it as follows.

<Spacer>
    <Child1 />
    <Child2 />
    <Child3 />
</Spacer>

We can control the space via props.

<Spacer space={5}>
    <Child1 />
    <Child2 />
    <Child3 />
</Spacer>

Upvotes: 2

Related Questions