0

I try to run child function in parent component.

I have a two child component with different functions. if active prop is true I try to call childOneFunction, otherwise, I should call childTwoFunction.

Here is my example code. What is the best way to do that?

const Parent = () => {
    const [active, setActive] = useState(true);
    function handleClickButton (){
        if(active){
            // call childOneFunction
        }else{
            // call childTwoFunction
        }
    }
    return (
      <div>
        <ChildOne active={active}/>
        <ChildTwo active={!active}/>
        <button onClick={handleClickButton}>Click</button>
      </div>
    );
  };

Child One component

  const ChildOne = () => {
    function childOneFunction() {
        return 'Child One Clicked'
      }
    return (
      <div>
        <h1>{childOneFunction}</h1>
      </div>
    );
  };

Child Two component

  const ChildTwo = () => {
    function childTwoFunction() {
        return 'Child Two Clicked'
      }
    return (
      <div>
        <h1>{childTwoFunction}</h1>
      </div>
    );
  };
Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42
ryouv
  • 25
  • 1
  • 5

1 Answers1

0

you can use ref to call the functions of the child component from the parent component, here is the full example:

import React, { forwardRef, useRef, useImperativeHandle , useState} from 
 'react';
export default function ParentFunction() {
const child1Ref = useRef();
const child2Ref = useRef();
const [active, setActive] = useState(false);

const handleClick = (nm=1) =>{
  if(active){
    child1Ref.current.showAlert()
  }else{
    child2Ref.current.showAlert()
  }
}

return (
    <div className="container">
        <div>
            Parent Component
        </div>
        <button
            onClick={handleClick}
>
        Call Function
        </button>

        <Child1 ref={child1Ref} />
        <Child2 ref={child2Ref}  />
    </div>
)
}


const Child1 = forwardRef((props, ref) => {
useImperativeHandle(
    ref,
    () => ({
        showAlert() {
            alert("Child 1 Function Called")
        }
    }),
)
return (
   <div>Child Component 1</div>
)
})


const Child2 = forwardRef((props, ref) => {
useImperativeHandle(
  ref,
  () => ({
      showAlert() {
          alert("Child 2 Function Called")
      }
  }),
)
 return (
 <div>Child Component 2</div>
)
})
Arfan ali
  • 429
  • 2
  • 5