Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 725
Claudio Castro Avatar asked Apr 08 '15 17:04

Claudio Castro


People also ask

How do I show a list item after click button in react native?

Make a Boolean flag in your component state and initiate it with false and then use it for showing the list. You can use FlatList for make a good list.


1 Answers

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.

like image 133
Okazaki Miyama Yuta Avatar answered Oct 16 '22 02:10

Okazaki Miyama Yuta