Hello I have a problem with calling a function passed as prop at the child component. Im trying to replicate my code with only the relevant lines of code:

class Parent extends Component {
  constructor(props) {
    super(props)
    this.press = this.press.bind(this)
  }
  press(param) {
    console.log(param)
  }
  renderItem = ({item}) => (
    <Child item={item} press={this.press} />
  )

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

class Child extends PureComponent {

  handlePress(param) {
    // do some stuff
    // call parent function
    this.props.press(param)
  }
  render() {
    const { id } = item
    return <Button onPress={() => this.handlePress(id)} />
  }
}

At the moment when pressing the button nothing happens, I got this already working with something like this:

<Child press={(param) => this.press(param)} />

however this causes performance issues.

How can I make this work ?

2 Answers

0
Kape On Best Solutions

After a while of testing I came to this solution:

class Parent extends Component {
  press = (param) => {
    console.log(param)
  }

  renderItem = ({item}) => (
    <Child item={item} press={this.press} />
  )

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

class Child extends Component {

  handlePress(param) {
    // do some stuff
    // call parent function
    this.props.press(param)
  }

  render() {
    const { id } = item
    return <Button onPress={() => this.handlePress(id)} />
  }
}
-1
mdeveloper On

It can be a good solution: instead of passing reference from button to parent class, remove the button from child class and use TouchableOpacity instead.

import {
  TouchableOpacity,
  View,
} from 'react-native'
class Parent extends Component {
  constructor(props) {
    super(props)
  }
  press(param) {
    console.log(param)
  }
  renderItem = ({item}) => (
      <TouchableOpacity onPress={()=>{this.press(item.id)}}>

        <Child item={item} />

      </TouchableOpacity>

  )

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

class Child extends PureComponent {

  render() {
    // just your view content
    const { id } = item
    return <View />
  }
}