Cactus
Cactus

Reputation: 924

this.props undefined in React native: TypeError: Cannot read property 'title' of undefined

I am trying to create a component that is a flatlist and to use probs to pass down some information to the component in the _renderItem function:

class ArticleList extends React.PureComponent {
  _renderItem = ({ item }) => (
    <DummyText title={item.title} />
  );

  render() {
    return (
      <View>
        <FlatList
          data={articles}
          renderItem={this._renderItem}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    );
  }
}

export default ArticleList;

This is the component for the FlatList.

The DummyText Component is very simple and just for trial purposes:

class DummyText extends React.Component {
  render() {
    console.log(this.props);
    return (
      <View>
        <Text>{this.props.title}</Text>
      </View>
    );
  }
}

export default DummyText;

However, when I do this, the this.probs part appears to be undefined and I get an error saying: TypeError: Cannot read property 'title' of undefined

I have made sure that the item has an attribute title and it works fine if the _renderItemdirectly creates <View><Text>{item.title}</Text></View>.

Upvotes: 0

Views: 719

Answers (2)

Jeff Gu Kang
Jeff Gu Kang

Reputation: 4879

Solution

Fix typo.

this.probs.title

=>

this.props.title

Why

Normally, undefined message say there is no value. Thus, you able to know easily what is wrong from title's parent value. And typo is happened often including me and it will be prevent by using linter as ESLint.

Upvotes: 1

Aditya
Aditya

Reputation: 3673

Actually, you are not passing item to your _renderItem function

render() {
   return (
     <View>
        <FlatList
           data={articles}
           renderItem={this._renderItem}
           keyExtractor={(item, index) => index.toString()}
        />
     </View>
   );
}

You have to pass item to your _renderItem function as,

render() {
   return (
     <View>
        <FlatList
           data={articles}
           renderItem={(item) => this._renderItem(item)}
           keyExtractor={(item, index) => index.toString()}
        />
     </View>
   );
}

Then same as you are using,

_renderItem = ({ item }) => (
   <DummyText title={item.title} />
);

Upvotes: 0

Related Questions