Search code examples
react-nativetvos

Centre item while scrolling in React Native tvOS


I am new to React native and i am creating a demo which lets items scroll vertically. Issue is when item is focused i need to get it centered. Lets suppose on UI only 3 items are visible and when i scroll among them than focused item should come in centre. Currently for out of focus item i have to press down key on d-pad twice.

import React, { useState, useRef, useCallback } from 'react';
import { FlatList, StyleSheet, Text, TouchableOpacity, View, Dimensions } from 'react-native';

const data = Array.from({ length: 20 }, (_, index) => index + 1);

const renderItem = ({ item }) => (
  <TouchableOpacity style={styles.item}>
    <Text style={styles.text}>{item}</Text>
  </TouchableOpacity>
);

export default function App() {

  return (
    <View style={styles.container}>
      <FlatList
        data={data}
        renderItem={({ item }) => renderItem({ item })}
        keyExtractor={(item) => item.toString()}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  item: {
    marginVertical: 8,
    height: 150,
    width: 100,
    backgroundColor: '#f9c2ff',
    justifyContent: 'center',
    borderRadius: 5,
  },
  selectedItem: {
    backgroundColor: '#ffb6c1',
  },
  text: {
    fontSize: 18,
    textAlign: 'center',
  },
});

enter image description here

I tried setting offset but it didn't work. i tried with scroll view that too failed.


Solution

  • I found the solution to this issue.

    We should use TouchableOpacity while working with tvOS. Touchable opacity with autoFocus flag will handle all situations.

    Detailed guide to Touchable Opacity