skip to Main Content

i am a react native beginner and struggling with re-rendering a component despite state change, here is the omitted version of my component:

export default function HomeScreen({ navigation }) {
  const { getItem } = useAsyncStorage("todo");
  const [selectedItems, setSelectedItems] = useState([]);

  function renderCard({ item }) {
    return (
      <TouchableHighlight
        onLongPress={() => {
          setSelectedItems((selectedItems) => [...selectedItems, item.title]);
        }}
        underlayColor="gray"
      >
        <Card
          style={
            selectedItems.includes(item.title)
              ? styles.cardSelected
              : styles.cardNotSelected
          }
        >
          <Card.Title style={styles.cardTitle}>{item.title}</Card.Title>
        </Card>
      </TouchableHighlight>
    );
  }

  useEffect(() => {
    const unsubscribe = navigation.addListener("focus", getTodoList);

    return unsubscribe;
  }, []);

  return (
    <View>
      <FlatList
        refreshing={loading}
        onRefresh={getTodoList}
        style={styles.list}
        data={items}
        renderItem={renderCard}
        keyExtractor={(item) => item.id}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  cardSelected: {
    backgroundColor: "#444333",
  },
  cardNotSelected: {
    backgroundColor: "#ff2f2f",
  },
});

I basically want to change background color of a Card when a card is longpressed, any help is appreciated!

2

Answers


  1. Chosen as BEST ANSWER

    I figured out the problem. Re-rendering was fine, background color setting was wrong.

    Instead of:

    <Card
          style={
            selectedItems.includes(item.title)
              ? styles.cardSelected
              : styles.cardNotSelected
          }
    >
    

    I needed to use containerStyle to change the background of the card:

    <Card
          containerStyle={
            selectedId === item.id
              ? styles.cardSelected
              : styles.cardNotSelected
          }
    >
    

  2. <FlatList
      {…otherProps}
      extraData={selectedItems}
    />
    

    Use the extraData prop. It will cause the FlatList to re render when the values provided changes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search