8

I can passdown props with spread operator. ie,

<Component x={props.x} y={props.y} />

is equal to:

<Component {...props} />

And we can use it in the component definition with the same name.

My question is how can I pass a function like this? What is the equivalent code for below?

<Component handleClick = {this.handleClick} 
   anotherHandleClick = {this.anotherHandleClick}/>

Edit:

Above line will pass down the function handleClick and anotherHandleClick to the child. Is there something like <Component {...Fns} /> so that every function will pass down as props with the same name.

Asim K T
  • 16,864
  • 10
  • 77
  • 99
  • 2
    I am not sure I understand your question, because you asked it then immediately answered it with the last piece of code. – M0nst3R Oct 24 '17 at 11:56
  • 1
    @GhassenLouhaichi he want's something like this `let handleClick = this.handleClick; ` but in one line, which to my knowledge is impossible. – Anis Smail Oct 24 '17 at 12:17

1 Answers1

9

Yes , You can do it like :

1) First way :

render() {
   const methods = { handleClick : this.handleClick };
   return(
        <Component {...methods} />
   )
}

2) Second way :

Without using any extra varible const methods = { handleClick : this.handleClick };

render() {
    return(
        <Component {...this.constructor.prototype} />
        // or
        <Component {...this.__proto__} />
    )
}

NOTE : The second method is not preferable as it gives all the access of class to a child, all means all, constructor, render everything....

I just want to show the ways we can achieve, still if there are lots of functions we can go with second way too, but be careful with that.


Here is the working example for both of above, please have a look :

https://stackblitz.com/edit/react-parent-click-prop

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122