Prashant Kumar
Prashant Kumar

Reputation: 31

FlatList ref issue

I am not getting ref of the flatlist always getting

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

I am beginner in react-native

export default class ListData extends Component {
  constructor(props) {
    super(props);
    this.state = {
      flatListRef: null
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={countryList}
          ref={ref => (this.state.flatListRef = ref)}
          style={{ flex: 1 }}
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          renderItem={({ item, index }) => (
            <View style={[styles.ListViewContainer]}>
              <Text style={styles.countryTxt}>
                <Text> +{item.code}</Text>
                <Text> {item.CountryName} </Text>
              </Text>
            </View>
          )}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 40,
    backgroundColor: "white"
  }
});

Upvotes: 1

Views: 2136

Answers (3)

Friendly-Robot
Friendly-Robot

Reputation: 1164

Try passing ref={null} to your list item component.

renderItem={({ item, index }) => (
  <View style={[styles.ListViewContainer]} ref={null}>

Upvotes: 0

Prashant Kumar
Prashant Kumar

Reputation: 31

Using import { FlatList } from "react-native" instead of import { FlatList } from 'react-native-gesture-handler';

is working. But I am still want to why it's not working with 'react-native-gesture-handler'. while list is displaying correctly but ref is not getting.

Upvotes: 1

mindthegab
mindthegab

Reputation: 31

try this:

in your constructor

this.flatListRef = React.createRef()

and then in your FlatList you do:

<FlatList ref={this.flatListRef} ...

Upvotes: 0

Related Questions