0

In render() of my RN component class I call functional component A which loads a Carousel. This Carousel in A then calls functional component B in its renderItem prop. B contains a FlatList w ref defined as <FlatList ref={ref => (this.list = ref)} />.

So A is successfully accessing this.list.scrollToIndex() in an onTouch call defined in A. What I need to do is call this.list.scrollToOffset() in B where the FlatList and the ref are defined - but when I do that I get an error TypeError: TypeError: null is not an object (evaluating '_this.list.scrollToOffset')

I've tried using React.createRef() at the class level but that is not working either.

Here is the code:


  //component B
  renderList = () => {
    if (scrollPosition>0) {
        //this call to list fails
        this.list.scrollToOffset({
            offset: scrollPosition
        })
    }
    return (
      <FlatList
        ref={ref => (this.list = ref)}
        ...
      />
    )
  }

  //component A
  renderCarousel = () => {
    return (
        <View style={{ flex: 1 }}>
        <View>
            <TouchableOpacity
            onPress={() => {
                this.list.scrollToIndex({ index: 0 }) //this call to list works
            }}
            >
            </TouchableOpacity>
        </View>
        {
            showList && (
            <Carousel
                renderItem={this.renderList}
            />
            )
        }
        </View>
    )
  }

I'm guessing I'm in that weird and dreaded js this zone. Any ideas?? TIA!

mutable2112
  • 439
  • 4
  • 15
  • 1
    It's hard to understand what's going in in this code `renderList` looks like a method in a class to me, but you have it labeled "component B" is it a method inside component B? Then component B is not functional like you say it is. Anyway you call `this.list.scrollToOffset` every render, and during first render, clearly, ref isn't set yet hence the error. You should call `this.list.scrollToOffset` only in response to events, not on every render – Max Dec 31 '19 at 21:24
  • @Max yea, missed the fact that it's not rendered yet - thx – mutable2112 Jan 02 '20 at 10:24

0 Answers0