Claudio Castro
Claudio Castro

Reputation: 539

How to change a ListView Item as Marked In React-Native

I am using a ListView as a selector, everything is working but I cannot change the visual state of the element of the list:

this.state = {
  dataSource: dataSource.cloneWithRows([
                        {
                            provincia:"Bocas del Toro",
                            capital: "Bocas del Toro", 
                            selected:false,
                        },
                        {
                            provincia:"Coclé",
                            capital: "Penonomé", 
                            selected:false,
                        },
...

I change the data directly onPress like this:

rowPressed(rowData) {
    rowData.selected = true;
    this.props.onAreaSelect(rowData);
}

And I try to change the view like this:

<TouchableHighlight onPress={() => this.rowPressed(rowData)}
      underlayColor='#eeeeee' >
    <View>
      <View style={[styles.rowContainer, this.state.selected ? styles.selected :  styles.unselected ]}>
        <View  style={styles.textContainer}>
            <Text style={styles.title} 
                  numberOfLines={1}>{rowData.provincia}</Text>
            <Text style={styles.description} 
                  numberOfLines={1}>Capital: {rowData.capital}</Text>
        </View>

      </View>
      <View style={styles.separator} />
    </View>
  </TouchableHighlight>

Where styles.selected and styles.unselected are just 2 different defined styles.

Upvotes: 6

Views: 8382

Answers (1)

Okazaki Miyama Yuta
Okazaki Miyama Yuta

Reputation: 335

I can't tell what your onAreaSelect does here, but I had the similar issue, and the trick is to set dataSource state again corresponding to your changed rowData.

this.setState({
  dataSource: this.state.dataSource.cloneWithRows(
    // your new data here
  )   
}); 

For detailed implementation, React Native official ListView example did help me. https://facebook.github.io/react-native/docs/listview.html#examples

In their example, they use another object _pressData to store which row is being selected, and every time it's changed, they call _genRows to do the above.

Upvotes: 3

Related Questions