javascriptcssreactjsreact-nativemobile

How to make a view height fit the content inside in react native?


I'm building a mobile chat application and I came across this problem where I display the messages as text inside of a view, but apparently I can't make the messages appear in a certain height where it would fit inside the view. It's either the message is too long so it won't be displayed completely (there isn't enough space in the view) or the message appears but there is a lot of spaces after the text.

Please see the image that describes exactly the problem :

enter image description here

Here is my code :

1- Views :

if (chat.from !== CurrentUser) {
    temp_chat.push(
      <View key={i} style={styles.messageContainer1}>
        <View style={styles.thisUserText}>
          <Text style={styles.message}>{chat.msg}</Text>
        </View>
        <View style={styles.empty}></View>
      </View>
    );
  } else {
    temp_chat.push(
      <View key={i} style={styles.messageContainer2}>
        <View style={styles.empty}></View>
        <View style={styles.otherUserText}>
          <Text style={styles.message}>{chat.msg}</Text>
        </View>
      </View>
    );
  }

2- Style :

messageContainer1: {
  flexDirection: "row",
  marginBottom: 10,
  flex: 1,
},
messageContainer2: {
  flexDirection: "row",
  justifyContent: "flex-end",
  marginBottom: 10,
  flex: 1,
},
message: {
  fontSize: 16,
  color:"#fff",
  padding:10
},
empty: {
  flex: 1,
},
thisUserText: {
  backgroundColor: "#bf0010", // red 
  flex: 1,
  height: 100,
  borderRadius: 5,
  color:"#fff",
},
otherUserText: {
  backgroundColor: "#13283E", // dark blue
  flex: 2,
  height: 100,
  borderRadius: 5,
},

What I need to have is a dynamic height for the red and dark blue views, to make the text inside fit perfectly whether it's a long or short text. How can I achieve this ?

Thanks in advance 🙏


Solution

  • You can use flexBasis: auto

    Read here for more information