Search code examples
react-nativelayoutdynamicgrid-layouttablelayout

Align the cell heights for text items parsed from an API dynamically across multiple columns in React Native


I have three string items pulled from an external location with varying lengths. I’d like items in each row to align with one another. Also, I’d like the height of each item to reflect the length of its content. Short content will have short height, longer item will have higher cell height.

This is my current demo https://snack.expo.io/@leourushi/api-looping-01-threecalls-02

There are two challenges. One is between the three columns. “Title” and “published” are very short but “description” column tends to be a lot longer. Challenge #2 is that within the “description” section, each item comes with different length. Some are 4 lines, others are 5 or 6 lines and so on.

I’ve found a hack solution by assigning a hardcoded “height" value for each item as below:

cellHeight: {
height: 100,
},

100 is just an arbitrary number that seems to work for most item for now. But this is not a smart solution.

Has anyone tackled a similar challenge?


Solution

  • Yes fourtunately you can use height: 'auto' in react native

              <View style={styles.cellHeight}>
                <View style={styles.lineRow}>
                  <View style={styles.leftColumn}>
                    <Text> {item.title} </Text>
                  </View>
                  <View style={styles.midColumn}>
                    <Text> {item.description} </Text>
                  </View>
                  <View style={styles.rightColumn}>
                    <Text> {item.published.slice(5, item.published.length-13)} </Text>
                  </View>
                </View>
                <View style={styles.lineBreak} />
              </View>
    

    and your cellHeight style will look just like this:

      cellHeight: {
        height: 'auto',
      },
    

    Here is the snack i made based in yours.

    https://snack.expo.io/@mrcarjul/api-looping-01-threecalls-02