Search code examples
react-nativerefreact-native-listview

React Native - get refs of custom components in listview from renderRow


I have a ListView and am trying to access the refs of custom components I have written in the renderRow. I need to do some direct manipulation of the custom components so I need to get the refs of these.

It seems like other people have faced this issue too. I have tried following the recommendations in React Native: Refs in ListView and https://github.com/facebook/react-native/issues/897 but they don't seem to work for me. I have tried using the callback ref method as suggested. But, when I try printing out this.refs.listView.refs in componentDidMount, it is empty instead of returning customRef. How do I get the refs of the custom components from the renderRow function? Thank you

The class has the following functions:

componentDidMount() {
   console.log(this.refs.listView.refs);
},

getRef() {
   return 'customRef';
},

renderRow(rowData) {
   return (
     <CustomComponent ref={(ref)=>this.getRef} key={rowData.key} />
   );
},

render() {
   return (
      <ListView
         ref={'listView'}
         dataSource={this.state.dataSource}
         renderRow={this.renderRow} />
   );
}

Solution

  • First, you have a syntactical error in your code:

    renderRow(rowData) {
       return (
         //                                     \/ Missing execution of getRef
         <CustomComponent ref={(ref)=>this.getRef} key={rowData.key} />
       );
    },
    

    Second, the ref callback function has to actually store the ref somewhere to be referenced when you call this.refs.listView.refs. Where do you expect this value to come from? React doesn't allow for this sort of magical child ref storage, it's totally manual. You get a ref to this particular component in your callback, you have to figure out what to do with it.

    constructor(props) {
        super(props);
        this.rowRefs = [];
        this.storeRowRef = this.storeRowRef.bind(this);
    }
    componentDidMount() {
        console.log(this.rowRefs.length);
    }
    storeRowRef(rowRef) {
        this.rowRefs.push(rowRef);
    }
    renderRow(rowData) {
       return (
         <CustomComponent ref={storeRowRef} key={rowData.key} />
       );
    },
    ...