Home > Software engineering >  How to scroll to a specific element that can be modified? (React Native)
How to scroll to a specific element that can be modified? (React Native)

Time:06-09

I created a glossary and want to have access to the content of a specific letter if I click on the letter (I have a list of letter at the top of my page). But here is the issue: while I've found how to scroll down, I didn't find how to scroll to a specific element. It seems to be quite easy in HTML (Scroll to a specific Element Using html) but I didn't find a solution for React Native. I tried to create a ScrollToElement then use ref to fix it but it does not change if my variable change, it always go to the bottom of the page. Here is the code simplified:

  const fieldRef = React.useRef<HTMLInputElement>(null);
  const scrollToElement = () => fieldRef.current?.scrollIntoView();
...
 return (
    <View>
       <ScrollView>
          <View>
             {letter.map((letter) => {
              
                return (
                  <View>
                    <Text
                      onPress={scrollToElement}
                    >
                      {letter.name}
                    </Text>
                  </View>
                );
              })}
            </View>
            <View>
               {letter.map((letter) => {
                  return(
                    <View>

                    <div
                    ref={fieldRef}
                     >
                       <Text>
                          {letter.name}
                       </Text>
                    </div>

                   )
                  })}
             </View>
       </ScrollView>
    </View>
)






CodePudding user response:

have you tried react-native-scroll-to-element node package ?
first you need to npm i react-native-scroll-to-element in your project then you can use it as this example :

import React, { useRef } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { SpecialScrollView, SpecialView } from 'react-native-scroll-to-element';

export default function () {
  const viewRef = useRef()

  return (
    <SpecialScrollView>
      <View
        style={{
          height: 400,
          backgroundColor: 'red'
        }}
      />
      <SpecialView
        style={{
          height: 50,
          backgroundColor: 'blue'
        }}
        ref={viewRef}
      >
        <TouchableOpacity
          onPress={() => viewRef.current.focus()}
        >
          <Text
            style={{
              color: 'white',
              fontSize: 20,
              padding: 10
            }}
          >
            Focus here
        </Text>
        </TouchableOpacity>
      </SpecialView>
      <View
        style={{
          height: 800,
          backgroundColor: 'green'
        }}
      />
    </SpecialScrollView>
  );
}

more about this package in this link

  • Related