1

I'm trying to use scrollToIndex function of FlatList on react-native. However, when I switch the FlatList to createAnimatedComponent(FlatList), its ref becomes undefined.

Is there a way to keep FlatList's ref when I use createAnimatedComponent?

Thank you for your concern.

batatop
  • 979
  • 2
  • 14
  • 31

1 Answers1

8

currently createAnimatedComponent exposes a method called getNode() that should work for getting the ref to the underlying component. Here are 2 examples, one with the old refs and one with the new

// old ref style
class DemoComp extends Component {
  componentDidMount() {
    // setTimeout is needed for scrollToOffset ¯\_(ツ)_/¯
    setTimeout(() => {
      this.listRef.getNode().scrollToOffset({ offset: 100, animated: true });
    }, 0);
  }

  render() {
    return <Animated.FlatList ref={r => { this.listRef = r; }} {...otherProps} />;
  }
}

// new ref style
class DemoComp extends Component {
  listRef = React.createRef();

  componentDidMount() {
    // setTimeout is needed for scrollToOffset ¯\_(ツ)_/¯
    setTimeout(() => {
      this.listRef.current.getNode().scrollToOffset({ offset: 100, animated: true });
    }, 0);
  }

  render() {
    return <Animated.FlatList ref={this.listRef} {...otherProps} />;
  }
}

Eventually, in the future createAnimatedComponent will switch to "forwarded refs" which will only work with the new style. But that day is a long way away because of all the libraries that depend on the old style.

PS. If you're reading this in the distant future, you can check on the status of forwarded refs in createAnimatedComponent here: https://github.com/facebook/react-native/issues/19650

Mike Martin
  • 3,850
  • 1
  • 15
  • 18