Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to call function from component that is independent of each other

I have 3 components, one parent component which renders 2 child components. I need to access the function of the 1st child component from the 2nd child component.

Sample Code:

Parent Component:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Main extends React.Component {
myRef: React.RefObject<any>;
constructor(props: any) {
super(props);
  this.myRef = React.createRef();
}
  return (
    <div>
      {/* some code */}
      <ChildOne />
      <ChildTwo />
    </div>
  );

ChildOne:

function ChildOne() {
  const childOneFunction = () => {
    console.log("Hello from child one");
  };

  return <div>{/* some code */}</div>;
}
}

ChildTwo:

function ChildTwo() {
  useEffect(() => {
    childOneFunction();
  });

  return <div>{/* some code */}</div>;
}

I need call the childOneFunction() from childTwo component. Is it possible without any 3rd party library like redux?

>Solution :

Maybe you can try with forwarding refs and useImperativeHandle.

Demo:

let ChildOne = React.forwardRef((props, ref) => {
  React.useImperativeHandle(ref, () => ({
    childOneFunction: () => {
      console.log('Hello from child one');
    },
  }));

  return <div>1</div>;
});

let ChildTwo = React.forwardRef((props, ref) => {
  return (
    <div
      onClick={() => {
        ref.current.childOneFunction();
      }}
    >
      2
    </div>
  );
});

export default function App() {
  const test = React.useRef();

  return (
    <div>
      <ChildOne ref={test} />
      <ChildTwo ref={test} />
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading