0

How could I call the function from a component to another component inside it? For example, when clicking the button on TestContentMain, I want to call the TestContent2's addOne immediately, but how and what is the best way to do it? Thanks

TestContentMain.js:

import React from 'react';
import TestContent2 from './TestContent2';

export default function TestContentMain() {
  return (
    <div>
      <TestContent2 />
      <button
        onClick={() => {
          alert('Want to call TestContent2->addOne immediately, but how?');
        }}
      >
        Test button
      </button>
    </div>
  );
}

TestContent2.js:

import React from 'react';

export default function TestContent2() {
  const countRef = useRef(0);

  const addOne = () => {
    countRef.current++;
    console.log(`Clicked ${countRef.current} times`);
  };

  console.log('I rendered!');

  return <button onClick={addOne}>Click me</button>;
}
Mario Petrovic
  • 5,868
  • 12
  • 32
  • 54
  • `TestContent2.js` is child of `TestContentMain`. This question is answered already on StackOverflow. You can see that https://stackoverflow.com/questions/37949981/call-child-method-from-parent – Himanshu Singh Dec 01 '21 at 04:06

0 Answers0