I'm using composition in React and would like to call a parent method. All of the examples I've found use inheritance.
Container component - Inserts a child component
interface ContainerProps {
children: ReactNode;
}
function Container(props: ContainerProps) {
const [showApply, setShowApply] = useState<boolean>(false);
return (
<>
<div>Children</div>
{props.children}
</>
);
// I want to call this method from the `children`
function calledByChild(){}
}
Composition - Needs to call Container method when button is clicked
function CombinedComponent() {
return <Container handleApplyClicked={handleApplyClicked}>
<Button type="primary" shape="round" onClick={tellContainerThatButtonWasClicked}>
</Container >
}
When the button is clicked in the CombinedComponent I would like it to inform the Container. The examples I've seen use inheritance and pass the parents method to the child but in this case the child is defining the parent within it.
How can this be achieved?
Update
I've tried adding this to the parent but the child components don't seem to have the extra property added.
{React.cloneElement(props.children as React.ReactElement<any>, { onClick: myFunc })}
Child interface/props
interface CombinedComponentProps{
// This value is always undefined
onClick?: () => void;
}
function CombinedComponent(props: CombinedComponentProps) {
...
// Undefined
console.log(props.onClick)
}