Home > Net >  How to align between two items inline left and right using flex in react native
How to align between two items inline left and right using flex in react native

Time:07-08

Here's what I'm trying to achieve: I want to align the 2 messages text label next to bargraph with background color green. The bargraph has dynamic width which renders coming from the backend and when size grows, the 2 messages label should also adjust and is always next to bargraph.

expected output

And here's what I have done sofar. It seems like that 2 messages won't show up next to bargraph with green background.

done sofar

component code:

                        <View style={[styles.container]}>
                            <View style={[styles.barGraph, styles.greenDeep]}>
                                <View style={{ flex: 6 }}>
                                    <Text style={styles.textLeft}>agree</Text>
                                </View>
                                <View style={{ flex: 6}}>
                                    <Text style={styles.textRight}>3 (60 %)</Text>
                                </View>
                            </View>
                            <View>
                                <Text>2 messages</Text>
                            </View>
                        </View>

css:

container: {
    flex: 1,
    flexDirection: "column",
    alignContent: "space-between",
},
textLeft: {
    fontSize: 12,
    color: 'white',
    textAlign: 'left'
},
textRight: {
    fontSize: 12,
    color: 'white',
    textAlign: 'right'
},
barGraph: {
    flexDirection: 'row',
    marginBottom: theme.SIZES.BASE,
    width: width - theme.SIZES.BASE * 10,
    padding: 10,
    borderRadius: 5
},
greenDeep: {
    backgroundColor: '#36d79a'
},

How would it be possible with react native's flex property? For live editing, visit snack here enter image description here

First you have to set your flexDirection of container class to column. Set maxWidth at other container classes, and create a new class for your message with justifyContent: 'center' attribute.

container: {
  flex: 1,
  flexDirection: "row", /*it was column*/ 
  alignContent: "space-between",
}

surveyDetailsContainer: {
    /* some code */
    maxWidth: 500,
},
container: {
    /* some code */
    maxWidth: 500,
},
   /* some other classes*/
barGraph: {
    /* some code */
    maxWidth: 400,
},

/*created a new class, included the minWidth and added 3 more new attributes*/
message: {
  minWidth: 5,
  maxWidth: 80,
  justifyContent: 'center',
  marginLeft: 5,
}

And then put the new message class into:

<View style={[styles.message]}>
  <Text>2 messages</Text>
</View>

Here is the whole code: https://snack.expo.dev/UwP7GVLzX

You can play around more with maxWidth, minWidth to make it responsive.

  • Related