Yellow Clock
Yellow Clock

Reputation: 465

React Native Flatlist how to set the first item as default selected?

I need that the flatlist like as below ,the first item "VISA" is selected by default ,how do I make it work ?

Thank you so much !

enter image description here

Here's my code :

Payment_Card(component):

 <FlatList 
        horizontal ={true}
        data = {payment_methods}
        keyExtractor ={card => card.id.toString()}
        renderItem ={({item,index})=>
        <Payment_Card
        img = {item.img}
        onPress ={()=>{
            setIndexValue(index);
            console.log(item);
            
        }}
        bgColor = {index===indexValue?colors.light_yellow:colors.white}
       
        />
    }
        />

Upvotes: 1

Views: 3636

Answers (2)

Pratik Adhikari
Pratik Adhikari

Reputation: 517

@Yellow Clock, Initialize the indexValue state as:

const [indexValue, setIndexValue] = useState(0);

Upvotes: 1

Arbnor
Arbnor

Reputation: 2352

I would pass a selected prop to the PaymentCard component. The PaymentCard component then controls the UI internally itself using the selected prop.

There are 2 ways how you set the first element as default:

  1. You do it on top of the index itself and check if the index equals 0
    <FlatList
      horizontal={true}
      data={payment_methods}
      keyExtractor={(card) => card.id.toString()}
      renderItem={({ item, index }) => (
        <Payment_Card
          img={item.img}
          onPress={() => {
            setIndexValue(index);
            console.log(item);
          }}
          selected={index === 0}
        />
      )}
    />
  1. Or you do it based on a provided state where you check if currentPaymentCard === VISA

Upvotes: 2

Related Questions