hanachan1026
hanachan1026

Reputation: 335

react native component passed as props cannot access props?

In my understandings React Native components have two ways to be rendered

・passing inside parents tag

・passing as parents'(?) props

For example I have this FlatList component

<FlatList
      ListHeaderComponent={MiddleRightLabelComponent}
      ItemSeparatorComponent={SeparatorComponent}
      data={this.state.dataSource}
      keyExtractor={item => item.title}
      // renderItem={({ item }) => <Text>{item.key}</Text>}
      renderItem={this._renderItem}
      style={styles.flatlist}
      {...this.props}
/>
_renderItem({ item, index }) {
    console.warn(this.props);
    return (
      <ListItem
        id={item.id}
        // onPressItem={this.props.openEditTaskModal.bind(this, true)}
        // selected={!!this.state.selected.get(item.id)}
        title={item.title}
      />
    );
}

In this _renderItem console.warn, I get (undefined) when I try to get (this.props).

I need to pass props into ListItem component.

Any idea?

Upvotes: 0

Views: 960

Answers (1)

Maxwelll
Maxwelll

Reputation: 2212

_renderItem is creating its own instance of this. In stateless components (or functions not bound to component class) you want to refer to the function params directy

const _renderItem = (props) => {
    console.warn(props);
    return (
      <ListItem
        id={props.item.id}
        title={props.item.title}
      />
    );
}

OR (with es6 destructuring):

const _renderItem = ({ item }) => {
    console.warn(item);
    return (
      <ListItem
        id={item.id}
        title={item.title}
      />
    );
}

Upvotes: 2

Related Questions