Defrian
Defrian

Reputation: 660

React-Native Callback Function / Method does not work

I read several tutorials but I don't understand why neither passing a callback function nor a callback method does not work.

When I console.log the Callback function is undefined.

Please help.

import React, { Component } from 'react';
import { FlatList } from 'react-native';
import { RecipeCard } from '../RecipeCard/RecipeCard';
import recipeData from '../../config/SampleDataRecipeList.json';

class RecipeList extends Component {
  constructor(props) {
    super(props);
    this.handlePress = this.handlePress.bind(this);
  }
  state = {};

  handlePress() {
    console.log('Handle Press');
  }

  handleClick = () => {
    console.log('Handle Click');
  };

  renderItem({ item }) {
    return (
      <RecipeCard
        title={item.title}
        persons={item.persons}
        time={item.time}
        uri={item.uri}
        onPress={this.handlePress}
      />
    );
  }

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

export { RecipeList };

Upvotes: 1

Views: 3383

Answers (2)

Praveen George
Praveen George

Reputation: 9725

What I suggest is that to use arrow functions like bellow:

  renderItem = item => {
    return (
      <RecipeCard
        title={item.title}
        persons={item.persons}
        time={item.time}
        uri={item.uri}
        onPress={this.handlePress}
      />
    );

Upvotes: 1

Defrian
Defrian

Reputation: 660

Solution was to change either to bind renderItem within the constructors or change it to a fat arrow function like

renderItem = ( ) => {...}

Upvotes: 1

Related Questions