I want my child componet handeClick() called when clicking on button on parent component

I have a parent component that inlude button.When i click on the button I can call the function inside the child component.here this is my parent component.

function App() {

  return (
    <div
      className="d-flex flex-column  border border-primary w-50 shadow container"
      id="quote-box"
    >
      <h2 id="text" className="m-4">
        {text}
      </h2>
      <h4 id="author" className="text-info text-end m-3">
        {author}
      </h4>
      <button id="new-quote" className="btn btn-primary" onClick={}>
        New Quote
      </button>
    <Theme />
    </div>
  );
}

this is my child component.And inside child component you can see handleClick function that I want to call by the button

export default function Theme() {


const {value,value2,value3}=useContext(GeneralContext)
const [text, setText] = value;
const [author,setAuthor] = value2;
const [bgColor,setBgColor]=value3

function random_bg_color() {
    var x = Math.floor(Math.random() * 120);
    var y = Math.floor(Math.random() * 120);
    var z = Math.floor(Math.random() * 120);
    const rgb = 'rgb(' + x + ',' + y + ',' + z + ')';
    return rgb;
  }

  const handleClick = ()=>{
    setBgColor(random_bg_color());
  }


    return (
        <div>
      
        </div>
    )

}

You could make a state in the parent component and pass it to the child component.
This state itself is a function which will be referenced to your handleClick function in the child component. In code it would be like:

Parent component:

function App() {
  const [childFunction, setChildFunction] = useState(null);
  const executeChildFunction = () => {
    childFunction();
  };

  return (
    <div>
      {/* Other stuff */}
      <button
        setChildFunction={setChildFunction}
        onClick={executeChildFunction}
      >
        Click on me to execute child function
      </button>
    </div>
  );
}

Child component:

export default function Theme({ setChildFunction }) {
  
  // your other stuff

  const handleClick = () => {
    setBgColor(random_bg_color());
  };

  useEffect(() => {
    setChildFunction(handleClick);
  }, []);

  return <div></div>;
}

now childFunction state in the parent component is refrencing handleClick in the child component.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.