Anoop K George
Anoop K George

Reputation: 1735

React Native, error looping through an array (Failed child context type:)

I have the below code to loop through an array.

export default function App() {
  const [x, setX] = useState([
    {name:'a'},{name:'b'}
  ]);
  return (
    <View >
      <FlatList
        data={x}
        renderItem={(item) => {
          return <Text>{item.name}</Text>;
        }}
      />
    </View>
  );

The above code gives below error

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

When I change

 <FlatList
            data={x}
            renderItem={(item) => {
              return <Text>{item.name}</Text>;
            }}
          />

To

 <FlatList
            data={x}
            renderItem={({item}) => {
              return <Text>{item.name}</Text>;
            }}
          />

The code is correct now and it works, see I changed (item) to ({item}) added curly braces .

Why is so ?

Upvotes: 0

Views: 942

Answers (3)

Anhdevit
Anhdevit

Reputation: 2104

As you can see link document https://reactnative.dev/docs/flatlist.html renderItem

renderItem({ item, index, separators });
  • item: (Object): The item from data being rendered.
  • index (number): The index corresponding to this item in the data array.
  • separators (Object)
  • highlight (Function)
  • unhighlight (Function)
  • updateProps (Function) select (enum('leading', 'trailing')) newProps (Object)

Example usage:

<FlatList
  ItemSeparatorComponent={
    Platform.OS !== 'android' &&
    (({ highlighted }) => (
      <View
        style={[
          style.separator,
          highlighted && { marginLeft: 0 }
        ]}
      />
    ))
  }
  data={[{ title: 'Title Text', key: 'item1' }]}
  renderItem={({ item, index, separators }) => (
    <TouchableHighlight
      key={item.key}
      onPress={() => this._onPress(item)}
      onShowUnderlay={separators.highlight}
      onHideUnderlay={separators.unhighlight}>
      <View style={{ backgroundColor: 'white' }}>
        <Text>{item.title}</Text>
      </View>
    </TouchableHighlight>
  )}
/>

Upvotes: 2

Burak Demirezen
Burak Demirezen

Reputation: 544

you should use the key prop flour. try again with the code below

<FlatList
    data={x}
    renderItem={({ item, index }) => (
        <Text key={index}>{item.name}</Text>
    )}
    keyExtractor={(item, index) => index.toString()}
/>

Upvotes: 2

M Muzzammil ijaz
M Muzzammil ijaz

Reputation: 178

Because the FlatList returns item object in which their is your items or array to be render!

its like

{ 
 items: {
   {name:'a'},
   {name:'b'}
  }
}

so we have to go to item first by destructuring by {item} and then access the inner objects.

Hope it will make understanding !

Upvotes: 0

Related Questions