Home > OS >  React Native Inverted Flatlist does not render absolute elements correctly
React Native Inverted Flatlist does not render absolute elements correctly

Time:08-26

Inverted Flatlist that contains absolute positioned elements doesn't seem to allow the absolute positioned elements to overlay previous components / items. Instead, they're forced underneath the previous component. I would like for the absolute positioned elements to render on top of the previous components.

Reproducible code samples:

List Container:

const MessageList = () => {
  const messages = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  const renderItem = ({ item, index }) => {
    return (
      <Message isLast={index === 0} />
    )
  }

  return (
    <FlatList
      data={messages}
      inverted
      style={{ flex: 1, paddingHorizontal: 16, paddingBottom: 16 }}
      renderItem={renderItem}
      ItemSeparatorComponent={() => <View style={{ marginVertical: 6 }} />}
    />
  )
}

export default MessageList

Message:

const Message = ({ ... }) => {
  return (
    <View>
      <Text style={{ backgroundColor: 'green', padding: 20 }}>Message here</Text>
      {
        isLast
          ? (
              <View style={{ backgroundColor: 'orange', position: 'absolute', bottom: 40, left: 0, right: 0, top: -20, zIndex: 20 }}>
                <Text>Absolute Positioned</Text>
              </View>

            )
          : null
      }
    </View>
  )
}

Result attached as image: Absolute positioned FlatList item

CodePudding user response:

I was able to solve this by making use of the CellRendererComponent prop. I was left with the following:

const MessageList = () => {
  const messages = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  const renderItem = ({ item, index }) => {
    return (
      <Message isLast={index === 0} />
    )
  }

  const renderCell = (props, index) => {
    return (
      <View style={[props.style, { zIndex: messages.length - props.index }]}>
        {props.children}
      </View>
    )
  }

  return (
    <FlatList
      data={messages}
      inverted
      style={{ flex: 1, paddingHorizontal: 16, paddingBottom: 16 }}
      renderItem={renderItem}
      ItemSeparatorComponent={() => <View style={{ marginVertical: 6 }} />}
      CellRendererComponent={renderCell}
    />
  )
}

which resulted in the following image: Results

  • Related