Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
React composition - How to call parent method

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)
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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)) {
      return React.cloneElement(child, { onClick: myFunc });
    }
  });
}

[edit] a working demo:

The following snippet demonstrate how the above approach could be used to read a child prop from the wrapper/parent component.
Please be aware that it might take a few seconds for the snippet to load and run; I did not investigate the reason for this, as it is out of the scope for the question.

const App = () => {
  return (
    <div>
      <h1>MyApp</h1>
      <WrapperComponent>
        <button id='btn1'>btn1</button>
        <button id='btn2'>btn2</button>
        <button id='btn3'>btn3</button>
        <div className='fakeBtn' id='div1'>div1</div>
      </WrapperComponent>
    </div>
  );
}

const WrapperComponent = ({ children }) => {
  const [clickedChildId, setClickedChildId] = React.useState();
  
  const myFunc = React.useCallback((id) => {
    setClickedChildId(id)
  }, [setClickedChildId]);
  
  React.useEffect(() => {
    clickedChildId && console.log(`the clicked child ID is ${clickedChildId}`);
  }, [clickedChildId]);
  
  return React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { onClick: () => myFunc(child.props.id) });
    }
  });
  
}

ReactDOM.render(<App />, document.querySelector('#mountNode'))
div.fakeBtn {
  background-color: #cdf;
  padding: 5px;
  margin: 3px 0;
  border: 1px solid #ccc;
  border-radius: 2px;
}
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id='mountNode'></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda