Amir J
Amir J

Reputation: 517

Component is not updating after changing state

Deep inside my application, I have a component as follows:

import React, {Component} from 'react'
import {View, Text, FlatList, TouchableOpacity} from 'react-native'

export default class Screen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selected: null
        }
    }

    renderText(item, index) {
        return (
            <TouchableOpacity
                style={{
                    borderWidth: 1, 
                    borderColor: '#bbbbbb', 
                    backgroundColor: this.state.selected == index ? 'blue' : 'white',
                    marginTop: index == 0 ? 0 : 10
                }}
                onPress={() => {
                    this.setState({selected: index})
                }}
            >
                <Text style={{padding: 10}}>{item.text}</Text>
            </TouchableOpacity>
        )
    }

    renderArray() {
        return (
            <FlatList 
                data={this.props.data}
                renderItem={({item, index}) => this.renderText(item, index)}
                keyExtractor={(item, index) => index.toString()}
            />
        )

    }

    render() {
        return (
            <View style={{margin: 10}}>
                {this.renderArray()}
            </View>
        )
    }
}

As you can see I'm rendering a FlatList and for each item, in the array, there is a Text component inside TouchableOpacity. When you click on each item, this.setState({selected: index}) will set the selected in state to the index of that item. this.state.selected is connected to the style of TouchableOpacity and I'm expecting with clicking on an item the background of it turns to blue, But this is not happening and there is no color change at all. I'll be grateful if you help me with this.

Upvotes: 4

Views: 102

Answers (2)

Nirmalsinh Rathod
Nirmalsinh Rathod

Reputation: 5186

      <FlatList 
            data={this.props.data}
            renderItem={({item, index}) => this.renderText(item, index)}
            keyExtractor={(item, index) => index.toString()}
            extraData={this.state}
        />

By passing extraData={this.state} to FlatList we make sure FlatList itself will re-render when the state.selected changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is also a PureComponent and the prop comparison will not show any changes.

Upvotes: 1

Eran
Eran

Reputation: 56

The reason is that FlatList only re-renders when this.props.data changes. You need to "hint" it to also watch changes for this.state. To do so, set extraData={this.state} on the FlatList. See https://facebook.github.io/react-native/docs/flatlist

Upvotes: 4

Related Questions