How to click programmatically a child component? react

I have two components, the parent and child. Currently I have these codes below. But unfortunately it returns an error:

TypeError: Cannot read property ‘click’ of null

For some reasons I want when button is click the Item component also will be click. But these codes below produces an error above. Anyone does know how to achieve it? import React, { useRef } from ‘react’;

const App = (props) => {
  const itemRef = useRef(null);
  
  return (
    <div>
    {dynamicBoolean ? (
         <button onClick={() => itemRef.current.click()}>
            click item
        </button>
    ) : (
        //more codes here
        <Item ref={itemRef} />
    )}  
    </div>
  );
};

export default App;

Child component would look like below (demonstration purposes, the code is very lengthly)

import React from 'react';

const Item = (props) => {
  
  return (
    <div>
        //some design here
    </div>
  );
};

export default Item;

Answer

You need useRef and you have to forward this ref to the Item component.

import React, { forwardRef, useRef } from 'react';

const Item = forwardRef((props, ref) => {
  return <li {...props}
  onClick={() => alert('clicked on Item')}
  ref={ref} >MyItem</li>
})

const App = (props) => {
  const itemRef = useRef(null);
  
  return (
    <div>
     <button onClick={() => itemRef.current.click()}>
        click item
    </button>
     
     
      <Item ref={itemRef} />
    </div>
  );
};

export default App;