Reputation: 139
I have two functional components in ReactJS, Parent and Child. I pass a function as a prop to the child from the parent component.
const export function Parent() {
const name = "parent";
function print_name() {
console.log(name);
}
return (
<Child print_name={print_name} />
)
};
child
const export function Child(props) {
const name = "child";
props.print_name(); //logs parent
return (<p>Child</p>)
}
In the above Component Child, the output on console is "parent" or in other words, the function print_name is bound(binding) to Parent Component. How can I make the function to not bind to the parent component, so that the print_name in the Child Components output "child".
Also, How does binding actually work in the functional-based components?
I don't want to create a separate function in Child component so that I can reuse my code from the Parent component.
Upvotes: 1
Views: 232
Reputation: 1
The function is executed in its context where it's defined, so it refers to the name
declared before its definition and log it, in order to make it print the child name you have to pass that name as parameter :
const export function Parent() {
const name = "parent";
function print_name(_name=name) {//by default takes the parent name
console.log(_name);
}
return (
<Child print_name={print_name} />
)
};
child :
const export function Child(props) {
const name = "child";
props.print_name(name); //logs child
props.print_name(); //without parameter it logs parent
return (<p>Child</p>)
}
In React.js the functions passed as props are use to modify parent state from child components, let's suppose that child component is an input that receives a name from parent to edit edit because in child component you cannot mutate props or parent state directly.
Another suggestion :
try to clone the function passed via props in the child component like :
const export function Child(props) {
const name = "child";
Function.prototype.clone = function() {
return new Function('return ' + this.toString())();
};
const print_child=props.print_name.clone();
print_child();//expected to log child
return (<p>Child</p>)
}
Upvotes: 1