Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 715
Diksha Goyal Avatar asked Sep 17 '26 21:09

Diksha Goyal


1 Answers

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>
  );
}
like image 196
Giorgi Moniava Avatar answered Sep 19 '26 09:09

Giorgi Moniava