Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda