1

Can you help me? I have two functional components and I need to use function from first component in second component. I want to use function "sayHello" in function onClicked, but I don't know how to do it.

import React from 'react';

type Props = {

}

const Component_1: React.FunctionComponent<Props> = () => {

  const sayHello = () => {

    console.log('----Hello');
    
  }
  
  return (
    <div className="">
      Component 1
    </div>
  );
};
    
export default React.memo(Component_1);


const Component_2: React.FunctionComponent<Props> = () => {

  const onClicked = () => {
    
    //How ???
    //Component_1.sayHello()

  }

  return (
    <div className="">
      
      <div onClick={onClicked}>
        Click me
      </div>

      <Component_1/>

    </div>
  );
};
2
  • Hi, Please look into the following link:- stackoverflow.com/questions/45262987/… This might resolve your issue. Commented Apr 28, 2022 at 16:24
  • there are components-class but I have components-function Commented Apr 28, 2022 at 16:56

1 Answer 1

2
const Component_1 = (props) => {
 const sayHello = () => {
  console.log("----Hello");
 };
 props.onClicked(sayHello);
 return <div className="">Component 1</div>;
};

const Component_2 = () => {
 let sayHello;
 const fn = function (sayHelloFromComp1) {
  sayHello = sayHelloFromComp1;
 };

 const onClicked = (e) => {
 //How ???
 //Component_1.sayHello()
 sayHello();
 };
 return (
  <div className="">
   <div onClick={onClicked}>Click me</div>
   <Component_1 onClicked={fn} />
  </div>
 );
};

export default Component_2;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.