How do I center an item within a React Native ListView?
Asked Answered
W

3

7

I'm trying to center an item within a horizontal listView when selected. My current strategy is to first measure the item and scroll to the x coordinates of the referenced item within the view.

enter image description here

Currently, any time I press an item ListView scrolls to the very end x: 538

Is there an easier way to implement this while keeping the code stateless / functional?

const ItemScroll = (props) => {

  const createItem = (obj, rowID) => {

    const isCurrentlySelected = obj.id === props.currentSelectedID

    function scrollToItem(_scrollViewItem, _scrollView) {
      // measures the item coordinates
      _scrollViewItem.measure((fx) => {
        console.log('measured fx: ', fx)
        const itemFX = fx;
        // scrolls to coordinates
        return _scrollView.scrollTo({ x: itemFX });
      });
    }
    return (
      <TouchableHighlight
        ref={(scrollViewItem) => { _scrollViewItem = scrollViewItem; }}
        isCurrentlySelected={isCurrentlySelected}
        style={isCurrentlySelected ? styles.selectedItemContainerStyle : styles.itemContainerStyle}
        key={rowID}
        onPress={() => { scrollToItem( _scrollViewItem, _scrollView); props.onEventFilterPress(obj.id, rowID) }}>
        <Text style={isCurrentlySelected ? styles.selectedItemStyle : styles.itemStyle} >
          {obj.title}
        </Text>
      </TouchableHighlight>
    )
  };
  return (
    <View>
      <ScrollView
        ref={(scrollView) => { _scrollView = scrollView; }}
        horizontal>
        {props.itemList.map(createItem)}
        {props.onItemPress}
      </ScrollView>
    </View>
  );
};

Update

With @Ludovic suggestions I have now switch to FlatList, I am not sure how trigger scrollToIndex with a functional component. Below is my new ItemScroll

const ItemScroll = (props) => {

  const {
      itemList,
      currentSelectedItem
      onItemPress } = props

  const renderItem = ({item, data}) => {
    const isCurrentlySelected = item.id === currentSelectedItem

    const _scrollToIndex = () => { return { viewPosition: 0.5, index: data.indexOf({item}) } }

    return (
      <TouchableHighlight
        // Below is where i need to run onItemPress in the parent
        // and scrollToIndex in this child.
        onPress={[() => onItemFilterPress(item.id), scrollToIndex(_scrollToIndex)]} >
        <Text style={isCurrentlySelected ? { color: 'red' } : { color: 'blue' }} >
          {item.title}
        </Text>
      </TouchableHighlight>
    )
  }
  return (
    <FlatList
      showsHorizontalScrollIndicator={false}
      data={itemList}
      keyExtractor={(item) => item.id}
      getItemLayout={(data, index) => (
          // Max 5 items visibles at once
          { length: Dimensions.get('window').width / 5, offset: Dimensions.get('window').width / 5 * index, index }
      )}
      horizontal        
      // Here is the magic : snap to the center of an item
      snapToAlignment={'center'} 
      // Defines here the interval between to item (basically the width of an item with margins)
      snapToInterval={Dimensions.get('window').width / 5}
      renderItem={({item, data}) => renderItem({item, data})} />
  );
};
Wilkes answered 20/4, 2017 at 4:10 Comment(0)
D
7

In my opinion, you should use FlatList

FlatList have a method scrollToIndex that allows to directly go to an item of your datas. It's almost the same as a ScrollView but smarter. Sadly the documentation is very poor.

Here is an example of a FlatList I did

let datas = [{key: 0, text: "Hello"}, key: 1, text: "World"}]

<FlatList
    // Do something when animation ended
    onMomentumScrollEnd={(e) => this.onScrollEnd(e)} 
    ref="flatlist"
    showsHorizontalScrollIndicator={false}
    data={this.state.datas}
    keyExtractor={(item) => item.key}
    getItemLayout={(data, index) => (
        // Max 5 items visibles at once
        {length: Dimensions.get('window').width / 5, offset: Dimensions.get('window').width / 5 * index, index}   
    )}
    horizontal={true}
    // Here is the magic : snap to the center of an item
    snapToAlignment={'center'}  
    // Defines here the interval between to item (basically the width of an item with margins)
    snapToInterval={Dimensions.get('window').width / 5}    
    style={styles.scroll}
    renderItem={ ({item}) =>
        <TouchableOpacity
            onPress={() => this.scrollToIndex(/* scroll to that item */)}
            style={styles.cell}>
            <Text>{item.text}</Text>
        </TouchableOpacity>
    }
/>

More about FlatList : https://facebook.github.io/react-native/docs/flatlist#__docusaurus

Decommission answered 20/4, 2017 at 7:29 Comment(5)
How would I specify the index for scrollToIndex? Is it the key, index in a visible items array , or index in the entire array?Wilkes
Index in the arrayDecommission
Would onPress={() => scrollToIndex({viewPosition: 0.5, index: data.indexOf({item})})} be a solution?Wilkes
Yes maybe better in your case! But an action should happened in scroll to.Decommission
My FlatList works but isnt scroll onPress since I'm using a functional component I'm not able to use this.scrollToIndex. I also need to pass functions to the parent in my onPress. Do you have any suggestions on how implement scrollToIndex?Wilkes
O
3

viewPosition prop will center your item.

flatListRef.scrollToIndex({ index: index, animated: true, viewPosition: 0.5 })
Outwardbound answered 24/2, 2021 at 11:13 Comment(0)
N
1
flatlistRef.current.scrollToIndex({
                    animated: true,
                    index,
                    viewOffset: Dimensions.get('window').width / 2.5,
                  });

You can try to put viewOffset inside the scrollToIndex property, it will handle your component offset, I use 2.5 to make it in middle of screen , because I show 5 item each section and one of focused item will be in middle of screen

Nisa answered 8/7, 2020 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.