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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With