Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!