Basically I have a function is my child component, I would like to pass this function as a prop and call it my parent component.
function parent() {
return (
<div>
<button onclick={handleAbort}></button>
</div>
);
}
function child() {
const handleAbort=() =>{
console.log('hello')
}
return (
<div>
</div>
);
}
CodePudding user response:
If both of these components are in the same file, and the function is not tied to any hooks, then define it outside the component. This way, you don't need to pass it through the component tree as a prop and it does not get redefined on re-renders.
const handleAbort = () => {
console.log('hello');
};
function parent() {
return (
<div>
<button onclick={handleAbort}></button>
</div>
);
}
function child() {
return <div></div>;
}
Hope this helps.
CodePudding user response:
You can't pass props from child to parent. what you can do is rendering the child in the parent component, and pass the function with props to the child. something like:
function Parent() {
const handleAbort=() =>{
console.log('hello')
}
return (
<div>
<Child handleClick={handleAbort} />
</div>
);
}
function Child({handleClick}) {
return (
<div>
<button onClick={handleClick}></button>
</div>
);
}
CodePudding user response:
As others have mentioned, you should try and pass from Parent to Child, what I think you may be trying to do is get a value from the Child to the Parent, which is often the case. In that case you still pass the function from the Parent to the Child, but pass a value from the Child to the Parent via args of the function - e.g.
function Parent() {
const handleAbortClick = (msg) => (e) => {
console.log(msg)
}
return (
<div>
<Child onAbortClick={handleAbortClick} />
</div>
);
}
function Child({ onAbortClick }) {
return (
<div>
<button onClick={onAbortClick('hello')}>Click me</button>
</div>
);
}
https://codesandbox.io/s/intelligent-haze-dj8rr3?file=/src/App.js
CodePudding user response:
Maybe you mean something like this?
function Parent() {
return (
<div>
<Child dataToParent={(msg) => console.log(msg)} />
</div>
);
}
function Child({dataToParent}) {
const handleAbort=() =>{
dataToParent('hello')
}
return (
<div>
<button onclick={handleAbort}></button>
</div>
);
}