Home > Enterprise >  React composition - How to call parent method
React composition - How to call parent method

Time:01-12

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?

CodePudding user response:

I recently had to do something similar and, inspired by this post, I ended up with:

const WrapperComponent = ({ children }) => {
  const myFunc = React.useCallback(() => {
    // ...
  }, []);
  
  return React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      React.cloneElement(child, { onClick: myFunc });
    }
  });
}

CodePudding user response:

You can do it by cloning the children, and giving it the props that you want:

React.cloneElement(children, {calledByChild})

This way, you add the function calledByChild to the children, so you can call it from the children component.

It could look like this:

const Parent = ({ children }) => {
  const func = () => console.log("click in Parent");
  return (
    <>
      <div>children</div>
      {cloneElement(children, {func})}
    </>
  );
};

const Children = ({func}) => {
  return <button onClick={func}>Click</button>;
};

Take a look at this article

  •  Tags:  
  • Related