React native: change the style of the ListView element by touch

I want to update the style of the ListView item when I click this item so that the end user knows that he has selected the item.

Listview

<ListView
    dataSource={this.state.dataSource}
    renderRow={this.renderFriend}
/>

String Renderer:

renderFriend(friend) {
  return (
    <TouchableHighlight onPress={ ??? }>
      <View style={styles.friendItem}>
        <View style={styles.profilePictureContainerNoBorder}>
          <Image
            source={{uri: 'https://graph.facebook.com/' + friend.id + '/picture?width=500&height=500'}}
            style={styles.profilePicture}
          />
        </View>
        <Text style={styles.profileName}>{friend.name}</Text>
      </View>
    </TouchableHighlight>
  );
}

How can I change the style of the second view when the user activates TouchableHighlight?

I would also like to add the selected object to an array of selected objects.

+4
source share
1 answer

You must use the state of the component and store the selected friends ids on click in it TouchableHighlight.

Sort of:

constructor(props) {
  super(props);
  this.state = {
    selectedFriendIds: [],
  }
}

selectFriend(friend) {
  this.setState({
    selectedFriendIds: this.state.selectedFriendIds.concat([friend.id]),
  });
}

renderFriend(friend) {
  const isFriendSelected = this.state.selectedFriendIds.indexOf(friend.id) !== -1;
  const viewStyle = isFriendSelected ?
    styles.profilePictureContainerSelected : styles.profilePictureContainerNoBorder;

  return (
    <TouchableHighlight onPress={ () => this.selectFriend(friend) }>
      <View style={styles.friendItem}>
        <View style={viewStyle}>
          <Image
            source={{uri: 'https://graph.facebook.com/' + friend.id + '/picture?width=500&height=500'}}
            style={styles.profilePicture}
          />
        </View>
        <Text style={styles.profileName}>{friend.name}</Text>
      </View>
    </TouchableHighlight>
  );
}
+6
source

Source: https://habr.com/ru/post/1618787/


All Articles