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

247
Visualizações
React: communicate between parent and child component

I want to communicate from my Child component (a input form) to my parent component (popup) weather or not there is any data in the child.

The issue im facing is that the child component isn't a set child in the code it gets there with the {props.children} tag:

App.js structure:

<div>
   <Popup>
      </Child>
   </Popup>
</div>

Popup.js structure:

<div>
   {this.props.children}
</div>

Is there a way to do this without using a window.* variable or frankenstein-ing a stateSet/stateRead function in my App.js?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I have done some risky stuff here, but it gets the job done:

import React, { useEffect, useState } from "react";

export default function NewApp() {
  return (
    <Parent pProps="boss">
      <Child text="Hello1" />
      <Child text="Hello2" />
      <Child text="Hello3" />
    </Parent>
  );
}

function Parent(props) {
  const [children, setChildren] = useState([]);

  function communicateWithMe(val) {
    console.log("I am called", val);
  }

  useEffect(() => {
    let _children = React.Children.map(props.children, (child) => {
      console.log("Parent child", child);
      return {
        ...child,
        props: {
          ...child.props,
          callBack: communicateWithMe
        }
      };
    });

    console.log("_children", _children);
    setChildren(_children);
  }, []);

  return (
    <div
      style={{
        background: "black",
        color: "white"
      }}
    >
      {children}
    </div>
  );
}

function Child(props) {
  console.log(props);
  return (
    <div>
      <p>{props.text}</p>
      {props.callBack && (
        <button
          onClick={() => {
            props.callBack("children baby");
          }}
        >
          invoke Parent function
        </button>
      )}
    </div>
  );
}

here is the sandbox version to see it in action: https://codesandbox.io/s/sad-wood-5kuit3?file=/NewApp.js

Explaination:

What I aimed to do was to append the props on the children from the parent component. To do that, I casted the children (received in props by Parent) in to local state. Appended the prop to each child to have a callback function to communicate with the parent. The Parent component now returns the state variable that has the modified / appended props, instead of returns prop.children as it received!

EDIT:

As suggested, I have used React.Children to iterate over the children recieved by the parent in props.

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