react / react/react-native

SectionList.scrollToLocation not scrolling to section with itemIndex: 0

Abierto
#50,143 3 comentarios 4 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Component: SectionList Issue: Author Provided Repro
Lenguaje dominante
C++
Estrellas
127k
Forks
25.3k
Merge medio
1 d 23 h
PR fusionados (30 d)
4

Descripción

Description

When using the SectionList.scrollToLocation method with itemIndex: 0, the SectionList does not scroll to the expected section. The scroll works when itemIndex is set to 1. No errors are logged, and the onScrollToIndexFailed callback is never triggered.

Steps to reproduce

https://snack.expo.dev/@markwitt/sectionlist

1.	Create a SectionList with multiple sections and items with varying heights (see the code example below).
2.	Add a button that calls scrollToLocation with parameters sectionIndex: 1 and itemIndex: 0 to scroll to the second section (e.g., “Vegetables”).
3.	Press the button and observe that the list does not scroll to the desired section.
4.	Change itemIndex to 1 and notice that the scrolling occurs as expected.
import React, { useRef, useMemo } from 'react';
import { SectionList, Text, View, Button } from 'react-native';

// Function to generate sections with a specified number of items per section
const generateSections = () => {
 const createItems = (prefix, count) => {
   return Array.from({ length: count }, (_, i) => ({
     label: `${prefix} ${i + 1}`,
     // Random height between 50 and 150
     height: 50 + Math.floor(Math.random() * 100),
   }));
 };

 return [
   { title: 'Fruits', data: createItems('Fruit', 15) },
   { title: 'Vegetables', data: createItems('Vegetable', 15) },
   { title: 'Grains', data: createItems('Grain', 15) },
 ];
};

export default function App() {
 const sectionListRef = useRef(null);
 // useMemo to generate sections only once on mount
 const sections = useMemo(() => generateSections(), []);

 const scrollToSection = () => {
   if (sectionListRef.current) {
     sectionListRef.current.scrollToLocation({
       sectionIndex: 1, // "Vegetables" section
       itemIndex: 0,    // Using 0 does not scroll; using 1 works correctly
     });
   }
 };

 return (
   <View style={{ flex: 1, paddingTop: 40 }}>
     <Button title="Scroll to Vegetables" onPress={scrollToSection} />
     <SectionList
       ref={sectionListRef}
       sections={sections}
       keyExtractor={(item, index) => item.label + index}
       renderItem={({ item }) => (
         <View
           style={{
             height: item.height,
             justifyContent: 'center',
             borderBottomWidth: 1,
             borderColor: '#ccc',
           }}
         >
           <Text style={{ padding: 10 }}>
             {item.label} (Height: {item.height})
           </Text>
         </View>
       )}
       renderSectionHeader={({ section: { title } }) => (
         <Text
           style={{
             padding: 10,
             fontWeight: 'bold',
             backgroundColor: '#eee',
           }}
         >
           {title}
         </Text>
       )}
     />
   </View>
 );
}````


### React Native Version

0.76.7

### Affected Platforms

Runtime - iOS

### Output of `npx @react-native-community/cli info`

```text
npx @react-native-community/cli info 
(node:84710) ExperimentalWarning: CommonJS module /Users/mark/.nvm/versions/node/v23.2.0/lib/node_modules/npm/node_modules/debug/src/node.js is loading ES Module /Users/mark/.nvm/versions/node/v23.2.0/lib/node_modules/npm/node_modules/supports-color/index.js using require().
Support for loading ES Module in require() is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Need to install the following packages:
@react-native-community/cli@18.0.0
Ok to proceed? (y) y

(node:84739) ExperimentalWarning: CommonJS module /Users/mark/Projects/hivemind-expo/node_modules/debug/src/node.js is loading ES Module /Users/mark/Projects/hivemind-expo/node_modules/debug/node_modules/supports-color/index.js using require().
Support for loading ES Module in require() is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
(node:84739) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
info Fetching system and libraries information...
System:
 OS: macOS 15.2
 CPU: (10) arm64 Apple M1 Pro
 Memory: 189.44 MB / 16.00 GB
 Shell:
   version: "5.9"
   path: /bin/zsh
Binaries:
 Node:
   version: 23.2.0
   path: ~/.nvm/versions/node/v23.2.0/bin/node
 Yarn:
   version: 1.22.22
   path: ~/.nvm/versions/node/v23.2.0/bin/yarn
 npm:
   version: 10.9.0
   path: ~/.nvm/versions/node/v23.2.0/bin/npm
 Watchman: Not Found
Managers:
 CocoaPods:
   version: 1.16.2
   path: /opt/homebrew/bin/pod
SDKs:
 iOS SDK:
   Platforms:
     - DriverKit 24.1
     - iOS 18.1
     - macOS 15.1
     - tvOS 18.1
     - visionOS 2.1
     - watchOS 11.1
 Android SDK: Not Found
IDEs:
 Android Studio: 2024.2 AI-242.23339.11.2421.12550806
 Xcode:
   version: 16.1/16B40
   path: /usr/bin/xcodebuild
Languages:
 Java:
   version: 23.0.2
   path: /opt/homebrew/opt/openjdk/bin/javac
 Ruby:
   version: 2.6.10
   path: /usr/bin/ruby
npmPackages:
 "@react-native-community/cli": Not Found
 react:
   installed: 18.3.1
   wanted: 18.3.1
 react-native:
   installed: 0.76.7
   wanted: 0.76.7
 react-native-macos: Not Found
npmGlobalPackages:
 "*react-native*": Not Found
Android:
 hermesEnabled: Not found
 newArchEnabled: Not found
iOS:
 hermesEnabled: Not found
 newArchEnabled: Not found

info React Native v0.78.1 is now available (your project is running on v0.76.7).
info Changelog: https://github.com/facebook/react-native/releases/tag/v0.78.1
info Diff: https://react-native-community.github.io/upgrade-helper/?from=0.76.7&to=0.78.1
info For more info, check out "https://reactnative.dev/docs/upgrading?os=macos".
Stacktrace or Logs
...
Reproducer

https://snack.expo.dev/@markwitt/sectionlist

Screenshots and Videos

No response

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con la implementación de SectionList.scrollToLocation y el reproductor de Snack enlazado, comparando sectionIndex: 1 con itemIndex: 0 frente a 1 en iOS con React Native 0.76.7. Sigue cómo se resuelve la sección objetivo para itemIndex: 0 y verifica la corrección con el caso reportado, asegurándote de que la segunda sección se desplace hasta quedar visible sin regresiones.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
ios, javascript, react-native
Área
mobile
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Activo
Claridad
Bastante claro
Aptitud para principiantes
55/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.