Home > Software design >  React - Catch event in sibling component
React - Catch event in sibling component

Time:07-11

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

CodePudding user response:

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

CodePudding user response:

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>
  );
}

CodePudding user response:

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.

CodePudding user response:

This is not difficult. You need to declare the function inside the parent component. Then component1 can use it and also component2 can trigger it. This functinality dont need redux store. And don't use redux store for this kind of simple things.Because redux use much memory and this lead to performance vulnerability. So if you need use state or function for two or three component, just use props.if you need more component use context Api. But you need to manage component more than this,use redux store.

  • Related