Skip to content
Advertisement

How to render check box inside flatlist

I created a checkbox inside my flatlist but when I click on the checkbox all the check boxes will render. I want to render the checkbox I press not the entire checkboxes. This is my code.

const ScreenCart = () => {
  const [checked, setChecked] = useState(false)
  const renderItem = ({ item, index }) => {
    return (
      <View style={styles.list}>
          <View style={{ flexDirection: 'row' }}>
            <CheckBox
              checkBoxColor={COLORS.ORANGE}
              isChecked={checked}
              onClick={() => setChecked(!checked)}
            />
            <Image
              source={item.image}/>
            <View>
              <Text numberOfLines={1} style={[styles.item, { width: 210 * rate }]}>{item.name} 
              </Text>
            </View>
          </View>
      </View>
    )
  }
  return (
    <View style={{ backgroundColor: COLORS.WHITE, flex: 1 }}>
      <View style={{ flex: 1 }}>
         <Flatlist
          data={TEMP_DATA_CART}
          renderItem={renderItem}
          keyExtractor={(item) => item.id.toString()}>
         />
      </View>
  )

this is my data.

TEMP_DATA_CART = [
  {
    id: '1', image: IMAGES.imgPromote, name: 'Sữa tắm Prunus - Premier Herb', value: 180000, quantity: 1, checked: false,
  },
  {
    id: '2', image: IMAGES.imgPromote, name: 'Sữa tắm Prunus - Premier Herb', value: 180000, quantity: 1, checked: false,
  },
  {
    id: '3', image: IMAGES.imgPromote, name: 'Sữa tắm Prunus - Premier Herb', value: 180000, quantity: 1, checked: false,
  },

Advertisement

Answer

you set a global state so it is selecting checkbox for all items

remove this

const [checked, setChecked] = useState(false)

set array of selected id’s

const [checked, setChecked] = useState([]);

on press set id in array and set check status from array

<CheckBox
    checkBoxColor={COLORS.ORANGE}
    isChecked={checked.includes(item.id)}
    onClick={() => {
      const newIds = [...checked];
      const index = newIds.indexOf(item.id);
      if (index > -1) {
        newIds.splice(index, 1); 
      } else {
        newIds.push(item.id)
      }
      setChecked(newIds)
    }}
   />

and in flatlist set extraData prop

<Flatlist
          data={TEMP_DATA_CART}
          renderItem={renderItem}
          extraData={checked}
          keyExtractor={(item) => item.id.toString()}>
         />

to retrive selected id’s you can get from checked array

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement