Home > Mobile >  How to scroll to an element of a list in react native?
How to scroll to an element of a list in react native?

Time:06-09

I was wondering if it was possible to scroll to an element of a list depending on another element of the list (ex : you avec a list [a,b,c,d], you put a touchableopacity with a b c d as text touchable and then you have multiple view, 1 for each elements of your list, and those view are created with a data.map. You then want that when you click on b, it will lead to the view of the element b) I have tried using react-native-scroll-to-element from How to scroll to a specific element that can be modified? (React Native) but it doesn't seems to work.

Here is the code :

<View>
  {letter.map((letter) => {
    return (
      <SpecialView>
        <Text
          onPress={() => {
            viewRef.current?.focus();
            scrollLetter = letter.name;
          }}
        >
          {letter.name}
        </Text>
      </SpecialView>
    );
  })}
</View>
<View>
  {letter.map((letter) => {
    return (
      <View>
        <div>
          <Text>{letter.name}</Text>
          <Text style={{ fontSize: 0 }}>
            {(scrollend = letter.name)}
            {/*la lettre actuelle */}
          </Text>
        </div>
      </View>
    );
  })}
</View>

CodePudding user response:

You might also try to use scrollTo() method of React Native's Scroll View.

If I understand your request correctly you should do something like this:

const ListPage = () => {
    const itemSize = 400
    const items = [{ name: 'a' }, { name: 'b' }, { name: 'c' }]

    const scrollView = useRef(null)

    return (
        <View style={{ flex: 1 }}>
            <View
                style={{
                    padding: 20
                }}
            >
                {items.map((item, index) => (
                    <TouchableOpacity
                        key={`head-${index}`}
                        style={{
                            backgroundColor: 'red'
                        }}
                        onPress={() => {
                            scrollView.current.scrollTo({ x: 0, y: itemSize * index, animated: true })
                        }}
                    >
                        <Text style={{ fontSize: 20 }}>{item.name}</Text>
                    </TouchableOpacity>
                ))}
            </View>
            <ScrollView ref={scrollView}>
                {items.map((item, index) => (
                    <View
                        key={`body-${index}`}
                        style={{
                            height: itemSize,
                            backgroundColor: 'green'
                        }}
                    >
                        <Text>{item.name}</Text>
                    </View>
                ))}
            </ScrollView>
        </View>
    )
}
  • Related