Berke
Berke

Reputation: 760

How to get a var/const from render in React-Native

I want to use animation in my flatlist items. I create animation function, and a style which located in render. But I cant use that style, because my renderItem function is out of render, what I can do about it? I mean, how we can use a const which is located in render, in other function which is located outside of render?

state = {
        animation: new Animated.Value(1)
    };

startAnimation = () => {
        Animated.timing(this.state.animation, {
            toValue: 1.5,
            duration: 1500
        }).start();
    }

_renderItem = ({item}) => {

   return(
            <Animated.View style={[animatedStyles]} >
                <TouchableOpacity onLongPress={() => this.activateItem(item.id)} onPress={() => this.startAnimation}>
                    <Image source={ images[item.item_id].uri } style={{width: 60, height: 60}}/>
                </TouchableOpacity>
            </Animated.View>
        );

    };


    render(){

        const animatedStyles = {
            transform: [
                {
                    scale: this.state.animation
                }
            ]
        };

        return(

            <View style={{flex: 1}}>

                <FlatList
                      numColumns={4}
                      contentContainerStyle={{flexDirection: 'column', justifyContent: 'space-between', marginRight: 10, marginLeft: 10}}
                      data={this.state.items}
                      renderItem={this._renderItem}
                      keyExtractor={this._keyExtractor}
                />

            </View>

        );

Upvotes: 0

Views: 618

Answers (1)

Sam O&#39;Brien
Sam O&#39;Brien

Reputation: 58

There's no reason why you can't access this.state in your _renderItem function so in this case it should be set here.

_renderItem = ({item}) => {
   return(
          <Animated.View style={{ transform: [{ scale: this.state.animation]}} >
            <TouchableOpacity onLongPress={() => this.activateItem(item.id)} onPress={() => this.startAnimation}>
            <Image source={ images[item.item_id].uri } style={{width: 60, height: 60}}/>
          </TouchableOpacity>
        </Animated.View>
    );

};

You'll also need to add this to your FlatList props. The extraData prop tells the rows to re-render whenever it changes.

extraData={this.state.animation}

Upvotes: 1

Related Questions