How to Fix Failed child context type: Invalid child context Warning in React Native

When you use components such as FlatList, you may get few warnings in react native. Even though these warnings may not appear as crucial it’s always better to fix those warnings. One such warning you may come across is given below.

Warning: Failed child context type: Invalid child context virtualizedCell.cellKey of type number supplied to CellRenderer, expected string.

react native flatlist warning

If you are having this warning while using FlatList then it’s because you are not providing a valid keyExtractor value. The keyExtractor prop helps to extract a unique key for a given item at the specified index. The unique id of each set of your data can be used as the key.

<FlatList
        keyExtractor={(item) => item.id}
        data={data}
        renderItem={({item}) => <Text>{item.title}</Text>}
      />

Always remind that the value of keyExtractor must be a string. See the complete example with no warnings.

import React, {useState, useEffect} from 'react';
import {View, Text, StyleSheet, FlatList} from 'react-native';

const App = () => {
  const [data, setData] = useState('');
  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);

  return (
    <View style={styles.container}>
      <FlatList
        keyExtractor={(item) => item.id.toString()}
        data={data}
        renderItem={({item}) => <Text>{item.title}</Text>}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
});

export default App;

In the above example, id is a number and that’s the reason it is converted to string when passing to the keyExtractor prop.

This warning is not limited to the FlatList and it may occur when you create any kind of lists. In such cases, pass your unique id to the key prop of your parent component of each child.

Similar Posts

Leave a Reply