Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native passing functions with arguments as props

Tags:

react-native

From what I have read its best to try and structure react apps with as many components as "dumb" renderers. You have your containers which fetch the data and pass it down to the components as props.

That works nicely until you want to pass functions down the chain that require arguments other than events.

class MyClass extends Component {


  _onItemPress (myId) {
    // do something using myId
  }

  render () {

    return <MyComponent myID={10} onPress={(myId) => this._onItemPress(myId)} />

  }

}

If I simply pass that as my onPress handler to MyComponent it won't return myId when called. To get around this I end up doing something like this.

export default ({myId, onPress) => {
  const pressProxy = () => {
    onPress(myId)
  }

  return (
    <TouchableHighlight onPress={pressProxy}>
      <Text>Click me to trigger function</Text>
    </TouchableHighlight>
  )
}

Am I doing this completely incorrectly? I would like to be able to have a simple component that I can re-use for list items where its sole function is to take a title, onpress function and return a list item to be used in ListViews renderRow function. Many of the onPress functions will require variables to be used in the onPress however.

Is there a better way?

like image 369
Sam Parmenter Avatar asked Oct 24 '16 13:10

Sam Parmenter


People also ask

How do you pass function with parameters as props in React native?

Define the function in the parent component. Pass it as a prop to the child component, e.g. <Child handleClick={handleClick} /> . Use the function in the child component.

Can you pass functions as props?

In React, there are several cases where you may want to pass a function (like onClick ) as a prop from a container to a child component — usually in order to let the child notify the parent of some event.

How do you pass a function as props in React native TypeScript?

To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.


1 Answers

The proper syntax would be something like this:

render () {
    let myId = 10;
    return <MyComponent myID={myId} onPress={() => this._onItemPress(myId)} />
}

Also, if you plan to use this inside _onItemPress (for example to call other methods in MyClass), you need to bind the scope like this:

render () {
    let myId = 10;
    return <MyComponent 
        myID={myId} 
        onPress={() => this._onItemPress(myId).bind(this)} />
}

...or you can bind it already in the constructor if you prefer:

constructor(props) {
    super(props);
    this._onItemPress = this._onItemPress.bind(this);
}
like image 180
Incinerator Avatar answered Sep 16 '22 12:09

Incinerator