How to use scrollTo function with argument is target not x and y in ListView?

514 views Asked by At

I have some issue with get x and y when I have multiple <View />, but I found that the argument target value is correct. So I decide to use it.

enter image description here

Here is my scrollTo function:

listView.scrollTo({ x, y, animated: true});

I change it like this but it's not working:

listView.scrollTo({ target, animated: true});

Is any way that using scrollTo with target ?

Any help would be appreciated.

1

There are 1 answers

4
Mukeyii On

You have to implement your own scrollToTarget Method in order to achieve this.

My solution would be sth. like this:

import * as React from 'react';
import { Text, View, StyleSheet, ScrollView, findNodeHandle, Button } from 'react-native';

export default class App extends React.Component {

  itemRefs = [];
  state = {
    dummyList: ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7"]
  };

  scrollToItem = () => {
    // Scroll to Item 2
    let refToScroll = this.itemRefs["Item 2"];
    refToScroll.measureLayout(findNodeHandle(this.listRef), (x,y) => {this.listRef.scrollTo({x: 0, y: y, animated: true})});
  }

  renderItems = ({ item }) => {
   return (
     <View ref={ref => {this.itemRefs[item] = ref}} style={{height: 200, margin: 20, borderWidth: 5, borderColor: "black"}}>
      <Text>{item}</Text>
     </View>
   )
  }

  render() {
    return (
      <View>
      <View style={{height: 25}}/>
      <Button containerStyle={{height: 55}} title="Click to scroll" onPress={this.scrollToItem} />
      <ScrollView
        ref={ref => {this.listRef = ref}}
        data = {this.state.dummyList}
        renderItem ={this.renderItems}
        >
        {this.state.dummyList.map(item => (
          <View ref={ref => {this.itemRefs[item] = ref}} style={{height: 200, margin: 20, borderWidth: 5, borderColor: "black"}}>
            <Text>{item}</Text>
          </View>
        ))}
        </ScrollView>
        </View>
    );
  }
}