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

208
Visualizações
React - Catch event in sibling component

My parent component looks like

<Tabs tabs={[
            {
              id: "Comp1",
              content: (
                <Comp1/>
              ),
            },
            {
              id: "Comp2",
              content: (
                <Comp2/>
              ),
            },
          ]}
        />

The requirement is to execute a function in comp1 on a button click in comp2 ?

What is the best way to handle such situations?

I am not much inclined towards handling it through redux-store, and have doubts over passing it through props

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

0

You can trigger event from first child to parent and then parent to second child. And have to use ref to perform any function call in the second child component from the parent. This is nice sample Here

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is example, in this scenario, Child will execute some function (which focuses an input) from FancyInput component, when clicking the div.

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focusInput: () => {
      inputRef.current.focus();
    },
  }));
  return <input ref={inputRef} />;
}
FancyInput = forwardRef(FancyInput);

let Child = (props) => {
  return <div onClick={props.callback}>Hello</div>;
};

export default function App() {
  let inputRef = useRef();
  let callback = () => inputRef.current.focusInput();
  return (
    <div>
      <FancyInput ref={inputRef} />
      <Child callback={callback} />
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

One of the solution is to uplift and define the function of comp1 inside the parent component and then pass it to both the children comp1 and comp2.

This way comp2 and comp1 both can access the function.

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