React native Flatlist with previous and next button

Viewed 19

...

I have Flatlist with array of images i want add previous and next button in this image to slide With dot indicator. I'm new to react native ...

Const images=[
    require('./assets/image1.png'),
  require('./assets/image2.png'),
  require('./assets/image3.png'),
  require('./assets/image4.png'),
  require('./assets/image5.png')
]

Const app =()=>{

return (
<FlatList 
    horizontal
    showsHorizontalScrollIndicator={false}
    data={images}
    renderItem={({ item }) => (
        <Image 
            source={item.images}
            style={{
                width:260,
                height:300,
                borderWidth:2,
                borderColor:'#d35647',
                resizeMode:'contain',
                margin:8
            }}
        />
    )}
/>

) }

1 Answers

First of all, you want to make sure every entry in your image objects has an attribute 'id' that is unique for each image. Without this id, the flatlist cannot keep track of which index its currently on and which index it needs to move to.

    const images = [
{
    id:0,
    image:'http://image.com;/0
},

{
    id:1,
    image:'http://image.com/1
},

{
    id:2,
    image:'http://image.com/2
},

]

Next use the keyextractor prop to set up a function to keep track of these id's.

  const keyExtractor = useCallback(item=>item.id.toString())
  <Flatlist keyExtractor={keyExtractor }
              
    
     />

Use the useRef hook to create a reference object for the flatlist. This will be used to manipulate the flatlist to move to whichever index you want.

const flatlistRef = useRef()
<Flatlist ref={flatlistRef}
          

 />

Now you can move between flatlist indexes by scrollToIndex by passing in whichever flatlist item index you want the list to scroll to.

If this is a large list, you can use another ref object to keep track of the the currently visible flatlistIndex via onViewableItemsChanged every time this function is fired. By passing this ref object you can always increment it or decrement it by one to scroll back and forth.

currentFlatlistIndex = useRef(null)
flatlistRef.current.scrollToIndex({ index: currentFlatlistIndex-1, animated: true })

And don't use arrow functions as props, the way you have done for renderItem. This will cause unnecessary re-renders. Always pass proper functions to props instead of relying on arrow functions.

Hope all this makes sense.

Related