3

I wrote two sample components to show what I'm trying to do. If the call was from the same class, I could do like below.

onClick={this.myFunc.bind(this, param1, param2)}

How do I do the same thing from a stateless component without the need to mess with binding 'this'.

onClick={props.onClick['need to add params']}

import React from 'react';
 
class BigComponent extends React.Component{
    constructor(props){
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }
    
    handleClick(param1, param2){
        // do something with parameters
    }

    render(){
        return(
            <div>
                <SmallComponent handleClick={this.handleClick}/>
            </div>
        );
    }
}

function SmallComponent(props){
 return(
        <div>
            <button onClick={ () => {props.handleClick('value_1', 'value_2')}}></button>
            <button onClick={ () => {props.handleClick('value_3', 'value_4')}}></button> 
            {/* how to do above without arrow functions, because I read that it's not optimized*/}
        </div>
    );
}
Hakan Karaduman
  • 109
  • 1
  • 2
  • 9

1 Answers1

4

Add a callback inside of this.myFunc.

this.myFunc = event => (param1, param2) => { ... do stuff }

In your top level component you can do:

handleClick={this.myFunc}

In your child, just do:

onClick={handleClick(param1, param2)}

Hope this is helps.

Alternatively you can do the following:

function SmallComponent(props){
    const handleClick = (param1, param2) => (event) => props.handleClick(param1, param2);

    return(
        <div>
            <button onClick={handleClick(param1, param2)}></button>
            ...
    );
}
pkuzhel
  • 317
  • 2
  • 5
  • but I want to send the parameters from the child components, values of param1 and param2 must come from child component to top level component. any way to call it without arrow function or bind – Hakan Karaduman Mar 17 '18 at 18:21
  • I updated my answer. Any time you have an onClick event and you want to pass params that are not coming from the event being passed by the onClick, you will have to do an arrow function (a callback) or you can create a function inside your view (I'll add an example to my answer). What's the issue with creating a function. Are you concerned about performance? – pkuzhel Mar 17 '18 at 21:33
  • Yes I'm concerned about performance because the reactjs website says that arrow function creates a new function on the memory each time it's called and it's bad for performance. – Hakan Karaduman Mar 17 '18 at 23:33
  • I work on a large scale application, you've reduced the arrow function to one (by declaring it as a variable). Yes, you will be creating a new function each render cycle but with modern computers, the amount of memory for creating such a simple function is negligible. We are not building rockets, just webapps ;) – pkuzhel Mar 19 '18 at 00:19