react-nativeorientationlandscapedevice-orientationflatlist

React-native flatlist item layout should adapt device orientation change


So I am creating flatlist of images. Which shows only one image at a time on the screen. Now if I rotate the device then the image which is in the landscape should be shown in full screen in landscape mode of the device.

I can not attach the code because it is too large. If anyone can give an example of this it will be great.

Just imagine this my rendetitem view of flatlist, here in place of text I have an image and it should be seen in landscape mode as device orientation change to landscape.

It should not affect the pagination of flatlist when device orientation comes again in portrait.

enter image description here


Solution

  • To update the dimensions of the images in the FlatList when the device is rotated to landscape mode, you can add an event listener to the Dimensions API and update the state with the new dimensions like this:

      const [imageDimensions, setImageDimensions] = useState({
        width: Dimensions.get('window').width - 40,
        height: Dimensions.get('window').height - 40,
      });
    
       useEffect(() => {
        const updateDimensions = () => {
          setImageDimensions({
            width: Dimensions.get('window').width - 40,
            height: Dimensions.get('window').height - 40,
          });
          setTimeout(() => {
            flatListRef.current?.scrollToIndex({ animated: false, index: selectedIndex });
          }, 100);
        };
    
        const dimensionsHandler= Dimensions.addEventListener('change', updateDimensions);
    
        return () => {
         dimensionsHandler.remove();
        };
      }, [selectedIndex]);
    
    // Image code
       <Image source={{ uri: 'https://url' }} style={imageDimensions} />
    

    Make sure that your flatList have this viewability Config

    
     const viewabilityConfig = useRef({
        minimumViewTime: 100,
        itemVisiblePercentThreshold: '90%',
      }).current;
    
    
      <FlatList
       ref={flatListRef}
       data={data}
       renderItem={renderItem}
       keyExtractor={(item) => item.id.toString()}
       horizontal
       initialScrollIndex={selectedIndex}
       onViewableItemsChanged={onViewableItemsChanged}
       viewabilityConfig={viewabilityConfig}
       pagingEnabled />
    

    You can check this working example from here.

    Hope it helps :D