aliep
aliep

Reputation: 1802

React Native FlatList - Calling A Function In The Render Method Which Returns A Component

I'm using FlatList to create a selectable list that highlights/ticks each item that is selected.

on index.js I'm using the component this way:

<SelectableList
  data={[{key: 'a'}, {key: 'b'}]}
  renderItem={(item) => <Text>{item.key}</Text>}
/>

on selectable-list.js I'm defining the list as:

renderItem = (item) => {
    return (
      <View>
        <Text>aaa</Text>
        {this.props.renderItem(item)}
        <Text>xxx</Text>
      </View>
    );
  }

render() {
  return (
    <FlatList
      data={this.state.data}
      renderItem={this.renderItem}
    />
  );
}

This is the output I get:

aaa

xxx

aaa

xxx

I expect it to be:

aaa

a

xxx

aaa

b

xxx

this Line is not working:

{this.props.renderItem(item)}

Upvotes: 0

Views: 8371

Answers (2)

Nick
Nick

Reputation: 1822

The argument to FlatList renderItem is of the form:

(info: {
   item: ItemT,
   index: number,
   ...
})

Meaning, your render function should look like this:

renderItem = ({item}) => {

NOT

renderItem = (item) => {

Upvotes: 4

aliep
aliep

Reputation: 1802

this is the console log of arg sent to renderItem, I had to pass item.item to the function to work

{ item: { key: 'a' },
index: 0,
separators: 
{ highlight: [Function: highlight],
unhighlight: [Function: unhighlight],
updateProps: [Function: updateProps] } }

Upvotes: 0

Related Questions