Issue
I made a carousel of images and now when I try to open the first screen where it contained the carousel, it gives me the error "undefined is not an object (evaluating ‘_this.flatList = flatList’)". At first my error was "Animated.event now requires a second argument for options", which I resolved it using {useNativeDriver: true} ( I got it from here (https://github.com/nysamnang/react-native-raw-bottom-sheet/issues/81)), but now its giving me the error that ‘this.flatList = flatList is undefined…..
any ideas on what could be the reason??
Here’s my code:
import React, { useState, useEffect } from 'react'
import { View, Text, StyleSheet, Dimensions, FlatList, Animated } from 'react-native'
import CarouselItem from './CarouselItem'
const { width } = Dimensions.get('window')
const Carousel = ({ data }) => {
const scrollX = new Animated.Value(0)
let position = Animated.divide(scrollX, width)
if (data && data.length) {
return (
<View>
<FlatList data={data}
ref = {(flatList) => {this.flatList = flatList}}
keyExtractor={(item, index) => 'key' + index}
horizontal
pagingEnabled
scrollEnabled
snapToAlignment="center"
scrollEventThrottle={16}
decelerationRate={"fast"}
showsHorizontalScrollIndicator={false}
renderItem={({ item }) => {
return <CarouselItem item={item} />
}}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { x: scrollX } } }
{useNativeDriver:true},
)}
/>
<View style={styles.dotView}>
{data.map((_, i) => {
let opacity = position.interpolate({
inputRange: [i - 1, i, i + 1],
outputRange: [0.3, 1, 0.3],
extrapolate: 'clamp'
})
return (
<Animated.View
key={i}
style={{ opacity, height: 10, width: 10, backgroundColor: '#27FFFF', margin: 8, borderRadius: 5 }}
/>
)
})}
</View>
</View>
)
}
}
const styles = StyleSheet.create({
dotView: { flexDirection: 'row', justifyContent: 'center', bottom:20, }
})
export default Carousel
Thank you in advanced for helping me resolve this issue
Solution
In your flatlist you are trying to assign a reference to a variable called flatlist that doesn’t exist:
<View>
<FlatList data={data}
--> ref = {(flatList) => {this.flatList = flatList}}
To solve this issue, you have to create the variable as a reference like this.
const flatlist = React.createRef();
or using hooks:
const flatlist = React.useRef(null);
const Carousel = ({ data }) => {
const scrollX = new Animated.Value(0)
let position = Animated.divide(scrollX, width)
// new line
const flatlist = React.createRef();
if (data && data.length) {
return (
<View>
<FlatList data={data}
Answered By – earayad
Answer Checked By – Willingham (FlutterFixes Volunteer)