Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass down a function with same name in React

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.

like image 622
Asim K T Avatar asked Oct 24 '17 11:10

Asim K T


People also ask

What is && operator in React?

The && is the exact same operator as you would find in any javascript expression, such as... if( condition1 && condition2) { } It is a feature of javascript that an expression of the form... (condition1 && condition2) will evaluate to condition2, if condition1 is true, or null if condition1 is false.

How do you pass a function from one component to another in react JS?

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.

How do you pass props between siblings in React?

To move data from a component to a sibling component, the simplest way is to pass a function from the parent component as a prop (i.e. "prop function") to its child that wants to update the data.


1 Answers

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

like image 118
Vivek Doshi Avatar answered Oct 02 '22 17:10

Vivek Doshi