0

Okay, straight to the point, I've heard that using arrow function is not ideal when used on render. Most people recommended to either use bind and normal function, or keeps using arrow function and use the parameter from the props.

But what if I have an array of objects that I iterate using Object.Values(myObjects).map(object => {...}) then I want to use the object as a parameter to the function I created before render.

class Card extends Component {
    onCardPress = (message) =>{
        alert(message)
    }

    render(){
        const { messages }; //from somewhere
        return(
            {Object.values(messages).map(message => 
                <TouchableOpacity
                    activeOpacity={0.8}
                    onPress={()=>{onCardPress(message)}}
                /> 
            }
        )
    }
}

One of the discussion that I read: Pass parameters to prop function without using an arrow function

  • You are forgetting `this`. It would be this: `onPress={()=>this.onCardPress(message)}` – Shubham Verma Oct 20 '20 at 12:29
  • I don't know what you've read but the problem is not using an arrow function there. This will be the same with regular functions. You're creating a new function on every render and passing it to a child component, this is the problem but most of the time (I mean really, most of the time) you can ignore this. – devserkan Oct 20 '20 at 12:32
  • @ShubhamVerma yes thank you, I didn't really look into it when I type it, but the point what I'm asking is, how do I use the function without using () => {} as I read that the arrow function is created whenever the component rendered. If I just use this.function, the function would just run without I even click it. – Bagas Naufal Insani Oct 20 '20 at 12:39
  • @devserkan Yeah but if I use regular function, I can declare it first, bind it on constructor, then just use this.function on onClick without needing to use arrow function. – Bagas Naufal Insani Oct 20 '20 at 12:39
  • Just check [this question](https://stackoverflow.com/questions/52788613/react-js-the-most-efficient-way-to-pass-a-parameter-to-an-event-handler-without/52788669#52788669) By the way, the accepted answer (unfortunately) is not right. Using a curried function doesn't help this situation. You can check my answer also you can see other answers as well. But again, most of the time you can ignore it and use an arrow function there. – devserkan Oct 20 '20 at 12:42

0 Answers0