Search code examples
cssreact-nativeavatartouchableopacity

React Native Avatar won't center align over text


I have an avatar and a text field inside a TouchableOpacity. I need both the avatar and the text to be center inside the TouchableOpacity and I need the avatar on one row and the text underneath every time even on screen resize.

The below code will place the avatar and the text side by side, and that is not correct:

<View>
  <TouchableOpacity>
    <View
      style={{
        flex: 1,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Avatar size={22} rounded source={{ uri: item1.avatarUrl2 }} />
      <Text
        style={{
          color: COLORS.purple_dark,
          fontSize: 12,
          textAlign: "center",
        }}
      >
        **The title of my Avatar will go Here**
      </Text>
    </View>
  </TouchableOpacity>
</View>

Solution

  • You want to keep Avatar in one row and the text just below it, then you need to comment out flexDirection: "row" from your code as by default in React components are placed in column. Or you can pass flexDirection: "column".

    <View>
      <TouchableOpacity>
        <View
          style={{
            flex: 1,
            flexDirection: "row", // comment it out or pass "column"
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <Avatar size={22} rounded source={{ uri: item1.avatarUrl2 }} />
          <Text
            style={{
              color: COLORS.purple_dark,
              fontSize: 12,
              textAlign: "center",
            }}
          >
            **The title of my Avatar will go Here**
          </Text>
        </View>
      </TouchableOpacity>
    </View>
    

    This will keep the components vertically aligned.

    enter image description here