React native flexbox how to align items vertically?

10,573

As the default flexDirection in React Native is column, flex items will stack vertically, hence the chart renders on a row of its own.

By using alignSelf: "flex-end" on the 2nd child View, which for columns control the cross axis (horizontal), it will right align.

To align them side-by-side, add flexDirection: "row" to the parent View.

You can also remove both the alignSelf properties on the two child View's, unless you want the 2nd View (alignSelf: "flex-end") align to bottom.

Updated code sample

<View style={{
    display: "flex",
    flexDirection: "row",
    flexWrap: "wrap"
}}>
    <View style={{width: "40%"}}>
        <Button
            BUY
        </Button>
        <View style={{alignSelf: "center", marginTop: "2%"}}>
            // A logo
        </View>
    </View>
    <View style={{ width: "40%"}}>
        <AreaChart
            style={{height: 250}}
            dataPoints={data}
            contentInset={{top: 30, bottom: 30}}
            curve={shape.curveNatural}
            svg={{
                fill: 'rgba(134, 65, 244, 0.2)',
                stroke: 'rgb(134, 65, 244)',
            }}
        />
    </View>
</View>
Share:
10,573
cbll
Author by

cbll

Updated on June 28, 2022

Comments

  • cbll
    cbll almost 2 years

    I'm a bit confused as to why this flex won't work.

     <View
    style={{
        display: "flex",
        flexWrap: "wrap"
    }}
    >
    <View style={{ width: "40%", alignSelf: "flex-start" }}>
        <Button BUY</Button>
        <View style={{ alignSelf: "center", marginTop: "2%" }}>// A logo</View>
    </View>
    <View style={{ width: "40%", alignSelf: "flex-end" }}>
        <AreaChart
            style={{ height: 250 }}
            dataPoints={data}
            contentInset={{ top: 30, bottom: 30 }}
            curve={shape.curveNatural}
            svg={{
                fill: "rgba(134, 65, 244, 0.2)",
                stroke: "rgb(134, 65, 244)"
            }}
        />
    </View>
    </View>;
    

    The intended layout I want to have is:

    BUTTON  |   <CHART
    LOGO    |   CHART>
    

    The button and logos centered together, and the chart taking up both "boxes" on the right.

    However, the above markup produces the following:

    BUTTON |
    LOGO   |
           | CHART
           | CHART
    

    They're doing the right thing but the Chart starts where the logo ends.

    Where did I go wrong with flexbox? How do I produce the right layout?