Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FlatList scrollToIndex not able to scroll properly for indexes that is in stickyHeaderIndices #43587

Open
menglaiq-sportsbet opened this issue Mar 21, 2024 · 5 comments
Labels
Component: FlatList Needs: Attention Issues where the author has responded to feedback. Needs: Repro This issue could be improved with a clear list of steps to reproduce the issue. Needs: Triage 🔍 Newer Patch Available

Comments

@menglaiq-sportsbet
Copy link

Description

Hi,

We are trying to upgrade our application from React Native 0.68 to current latest version of 0.73.4.

We have encountered a bug with FlatList, which was not an issue on RN version 0.68.

If we have items in the flatlist, that is defined in its stickyHeaderIndices, then we won't be able to use scrollToIndex to scroll to that sticky item. Instead, it will scroll you back to the top of the FlatList. Which is not an issue on RN 0.68.

To better demo this bug, I have created a simple app. The following is the App.js file. No other dependencies needed.

As you can see from the code, each item in the flatlist is a textinput field, whenever user focus on any of the input field. We would like to have that text field scroll to the top position of the screen, to save space in the bottom half of the screen for displaying the keypad.

For any item that is not in the stickyHeaderIndices, scrollToIndex works as expected. But for any item that is in stickyHeaderIndices, it will scroll you to the top of the list, rather than scroll you to the correct position.

For security reasons, my company laptop will not allow me to upload any video to public GitHub repos. But you can take the follow code and easily reproduce this issue.

import { StatusBar } from 'expo-status-bar';
import { FlatList, StyleSheet, Text, TextInput, View } from 'react-native';
import * as React from "react";

export default function App() {
  const flatListRef = React.useRef(null)

  const stickyList = [3,5];
  const DATA = [];
  for (let index = 0; index < 10; index++) {
    const element = {
      id: index,
      title: stickyList.includes(index) ? `${index} I am sticky Item` : `${index} Item`
    };
    DATA.push(element);
  };

  const handleFocus = (event, title) => {
    console.log(title);
    const index = title.match(/\d+/)[0];
    console.log(index);
    setTimeout(() => {
      flatListRef.current?.scrollToIndex({
        viewPosition: 0,
        index
      })
    })
  }
  const Item = (item) => {
    console.log(item)
    return(
        <View style={styles.item}>
          <Text style={styles.title}>{item.title}</Text>
          <TextInput
            onFocus={e => handleFocus(e, item.title)}
            style={{
              height: 40,
              borderColor: 'gray',
              borderWidth: 1,
            }}
          />
        </View>
      );
  };

  const renderItem = ({item}) => <Item title={item.title} />

  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>

      <FlatList
        ref={flatListRef}
        renderItem={renderItem}
        data={DATA}
        keyExtractor={item => item.id}
        stickyHeaderIndices={stickyList}
      />

      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});

Steps to reproduce

Use code provided in the description.
Start app.
Scroll through the list.
Tap on the sticky item's text input.
Scroll you back to the top of the list.

React Native Version

0.73.4

Affected Platforms

Runtime - Android, Runtime - iOS

Output of npx react-native info

info Fetching system and libraries information...
System:
  OS: macOS 13.6.4
  CPU: (8) arm64 Apple M1
  Memory: 87.02 MB / 16.00 GB
  Shell:
    version: "5.9"
    path: /bin/zsh
Binaries:
  Node:
    version: 18.17.1
    path: ~/.nodenv/versions/18.17.1/bin/node
  Yarn:
    version: 1.22.19
    path: ~/.nodenv/versions/18.17.1/bin/yarn
  npm:
    version: 9.6.7
    path: ~/.nodenv/versions/18.17.1/bin/npm
  Watchman:
    version: 2023.02.13.00
    path: /Users/menglaiq/homebrew/bin/watchman
Managers:
  CocoaPods:
    version: 1.11.3
    path: /Users/menglaiq/.rbenv/shims/pod
SDKs:
  iOS SDK:
    Platforms:
      - DriverKit 22.1
      - iOS 16.1
      - macOS 13.0
      - tvOS 16.1
      - watchOS 9.1
  Android SDK:
    API Levels:
      - "25"
      - "28"
      - "30"
      - "31"
      - "32"
      - "33"
      - "34"
      - "34"
    Build Tools:
      - 28.0.3
      - 29.0.2
      - 30.0.0
      - 30.0.2
      - 30.0.3
      - 31.0.0
      - 32.0.0
      - 32.1.0
      - 33.0.1
      - 34.0.0
    System Images:
      - android-28 | Google APIs ARM 64 v8a
      - android-28 | Google APIs Intel x86 Atom_64
      - android-28 | Google ARM64-V8a Play ARM 64 v8a
      - android-29 | Google Play ARM 64 v8a
      - android-32 | Google APIs ARM 64 v8a
      - android-32 | Google Play ARM 64 v8a
    Android NDK: Not Found
IDEs:
  Android Studio: Not Found
  Xcode:
    version: 14.1/14B47b
    path: /usr/bin/xcodebuild
Languages:
  Java:
    version: 17.0.2
    path: /usr/bin/javac
  Ruby:
    version: 3.0.1
    path: /Users/menglaiq/.rbenv/shims/ruby
npmPackages:
  "@react-native-community/cli": Not Found
  react:
    installed: 18.2.0
    wanted: 18.2.0
  react-native:
    installed: 0.73.6
    wanted: 0.73.6
  react-native-macos: Not Found
npmGlobalPackages:
  "*react-native*": Not Found
Android:
  hermesEnabled: Not found
  newArchEnabled: Not found
iOS:
  hermesEnabled: Not found
  newArchEnabled: Not found

Stacktrace or Logs

No crash or anything

Reproducer

code in description

Screenshots and Videos

For security reasons, my company laptop will not allow me to upload any video to public GitHub repos. But you can take the follow code and easily reproduce this issue.

@github-actions github-actions bot added Needs: Author Feedback Needs: Repro This issue could be improved with a clear list of steps to reproduce the issue. labels Mar 21, 2024
Copy link

⚠️ Missing Reproducible Example
ℹ️ We could not detect a reproducible example in your issue report. Please provide either:
  • If your bug is UI related: a Snack
  • If your bug is build/update related: use our Reproducer Template. A reproducer needs to be in a GitHub repository under your username.

Copy link

⚠️ Newer Version of React Native is Available!
ℹ️ You are on a supported minor version, but it looks like there's a newer patch available - 0.73.6. Please upgrade to the highest patch for your minor or latest and verify if the issue persists (alternatively, create a new project and repro the issue in it). If it does not repro, please let us know so we can close out this issue. This helps us ensure we are looking at issues that still exist in the most recent releases.

@menglaiq-sportsbet
Copy link
Author

UPDATE: tried latest version 0.73.6, and the issue still persists.

@github-actions github-actions bot added Needs: Attention Issues where the author has responded to feedback. and removed Needs: Author Feedback labels Mar 21, 2024
@WilmarE
Copy link

WilmarE commented Mar 21, 2024

Descripción

Hola,

Estamos intentando actualizar nuestra aplicación de React Native 0.68 a la última versión actual de 0.73.4.

Hemos encontrado un error con FlatList, que no fue un problema en la versión 0.68 de RN.

Si tenemos elementos en la lista plana, que está definida en su stickyHeaderIndices, entonces no podremos usar scrollToIndex para desplazarnos a ese elemento fijo. En su lugar, lo llevará de regreso a la parte superior de FlatList. Lo cual no es un problema en RN 0.68.

Para demostrar mejor este error, he creado una aplicación sencilla. El siguiente es el archivo App.js. No se necesitan otras dependencias.

Como puede ver en el código, cada elemento de la lista plana es un campo de entrada de texto, siempre que el usuario se centre en cualquiera de los campos de entrada. Nos gustaría que ese campo de texto se desplace a la posición superior de la pantalla, para ahorrar espacio en la mitad inferior de la pantalla para mostrar el teclado.

Para cualquier elemento que no esté en stickyHeaderIndices, scrollToIndex funciona como se esperaba. Pero para cualquier elemento que esté en stickyHeaderIndices, lo desplazará a la parte superior de la lista, en lugar de desplazarlo a la posición correcta.

Por razones de seguridad, la computadora portátil de mi empresa no me permite cargar ningún video en repositorios públicos de GitHub. Pero puedes tomar el siguiente código y reproducir fácilmente este problema.

import { StatusBar } from 'expo-status-bar';
import { FlatList, StyleSheet, Text, TextInput, View } from 'react-native';
import * as React from "react";

export default function App() {
  const flatListRef = React.useRef(null)

  const stickyList = [3,5];
  const DATA = [];
  for (let index = 0; index < 10; index++) {
    const element = {
      id: index,
      title: stickyList.includes(index) ? `${index} I am sticky Item` : `${index} Item`
    };
    DATA.push(element);
  };

  const handleFocus = (event, title) => {
    console.log(title);
    const index = title.match(/\d+/)[0];
    console.log(index);
    setTimeout(() => {
      flatListRef.current?.scrollToIndex({
        viewPosition: 0,
        index
      })
    })
  }
  const Item = (item) => {
    console.log(item)
    return(
        <View style={styles.item}>
          <Text style={styles.title}>{item.title}</Text>
          <TextInput
            onFocus={e => handleFocus(e, item.title)}
            style={{
              height: 40,
              borderColor: 'gray',
              borderWidth: 1,
            }}
          />
        </View>
      );
  };

  const renderItem = ({item}) => <Item title={item.title} />

  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>

      <FlatList
        ref={flatListRef}
        renderItem={renderItem}
        data={DATA}
        keyExtractor={item => item.id}
        stickyHeaderIndices={stickyList}
      />

      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});

pasos para reproducir

Utilice el código proporcionado en la descripción. Iniciar aplicación. Desplácese por la lista. Toque la entrada de texto del elemento fijo. Desplácese hacia la parte superior de la lista.

Reaccionar versión nativa

0.73.4

Plataformas afectadas

Tiempo de ejecución: Android, Tiempo de ejecución: iOS

Salida denpx react-native info

info Fetching system and libraries information...
System:
  OS: macOS 13.6.4
  CPU: (8) arm64 Apple M1
  Memory: 87.02 MB / 16.00 GB
  Shell:
    version: "5.9"
    path: /bin/zsh
Binaries:
  Node:
    version: 18.17.1
    path: ~/.nodenv/versions/18.17.1/bin/node
  Yarn:
    version: 1.22.19
    path: ~/.nodenv/versions/18.17.1/bin/yarn
  npm:
    version: 9.6.7
    path: ~/.nodenv/versions/18.17.1/bin/npm
  Watchman:
    version: 2023.02.13.00
    path: /Users/menglaiq/homebrew/bin/watchman
Managers:
  CocoaPods:
    version: 1.11.3
    path: /Users/menglaiq/.rbenv/shims/pod
SDKs:
  iOS SDK:
    Platforms:
      - DriverKit 22.1
      - iOS 16.1
      - macOS 13.0
      - tvOS 16.1
      - watchOS 9.1
  Android SDK:
    API Levels:
      - "25"
      - "28"
      - "30"
      - "31"
      - "32"
      - "33"
      - "34"
      - "34"
    Build Tools:
      - 28.0.3
      - 29.0.2
      - 30.0.0
      - 30.0.2
      - 30.0.3
      - 31.0.0
      - 32.0.0
      - 32.1.0
      - 33.0.1
      - 34.0.0
    System Images:
      - android-28 | Google APIs ARM 64 v8a
      - android-28 | Google APIs Intel x86 Atom_64
      - android-28 | Google ARM64-V8a Play ARM 64 v8a
      - android-29 | Google Play ARM 64 v8a
      - android-32 | Google APIs ARM 64 v8a
      - android-32 | Google Play ARM 64 v8a
    Android NDK: Not Found
IDEs:
  Android Studio: Not Found
  Xcode:
    version: 14.1/14B47b
    path: /usr/bin/xcodebuild
Languages:
  Java:
    version: 17.0.2
    path: /usr/bin/javac
  Ruby:
    version: 3.0.1
    path: /Users/menglaiq/.rbenv/shims/ruby
npmPackages:
  "@react-native-community/cli": Not Found
  react:
    installed: 18.2.0
    wanted: 18.2.0
  react-native:
    installed: 0.73.6
    wanted: 0.73.6
  react-native-macos: Not Found
npmGlobalPackages:
  "*react-native*": Not Found
Android:
  hermesEnabled: Not found
  newArchEnabled: Not found
iOS:
  hermesEnabled: Not found
  newArchEnabled: Not found

Stacktrace o registros

No crash or anything

reproductor

código en la descripción

Capturas de pantalla y vídeos

Por razones de seguridad, la computadora portátil de mi empresa no me permite cargar ningún video en repositorios públicos de GitHub. Pero puedes tomar el siguiente código y reproducir fácilmente este problema.

@collinahn
Copy link

collinahn commented Apr 4, 2024

same here, ended up using scrollToOffset

or you can insert a dummy View component right before stickyHeader and use that index to scrollto.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component: FlatList Needs: Attention Issues where the author has responded to feedback. Needs: Repro This issue could be improved with a clear list of steps to reproduce the issue. Needs: Triage 🔍 Newer Patch Available
Projects
None yet
Development

No branches or pull requests

3 participants