How to call a method in a second js file from first js file on pressing the 'plus' key?

31 views Asked by At

I have 3 js files named, Tab.js, TabBody.js, TabDetail.js. TabDetail.js has displays a table with rows and columns. After the TabDetail.js gets loaded, when the user presses the '+' key, then a popup window should appear. The files are as follows:

Tab.js

import TabBody from './TabBody';

function Tab() {
  const [checked, setChecked] = useState(false);

  // Your HandlePressKeyEnter function
  const HandlePressKey = (event) => 
  {
    if (event.key === '+') {
      if (checked) {
        //How to call the OpenPopUp from 
        // TabBody.js?
        OpenPopUp();
      }
    }
  };


  useEffect(() =>{
  document.addEventListener('keydown', 
  handleKeyPress);
  return () => {
  document.removeEventListener('keydown', 
  handleKeyPress);
  };
  }, [])

  return (
    <div>
      {/* Pass the callback as a prop to the TabBody component */}
      <TabBody handleKeyPress={HandlePressKey} />
    </div>
  );
}

export default Tab;

TabBody.js


function TabBody(HandlePressKey) {

const [seeAll, setSeeAll] = useState(true)
const [staticheight, setStaticHeight]= useState(null)

  // Your HandlePressKeyEnter function
  const openPopUp = (event) => 
  {
     const data = ['a', 'b', 'c']
     if(seeAll){
       setStaticHeight(data)
     }
     //logic to open popup
  });

  return (
    <div>
      {/* Pass the callback to TabDetail.js*/}
<div> {staticHeight} </div>
      <TabDetail handleKeyPress={HandlePressKey} />
    </div>
  );
}

export default TabBody;

TabDetail.js


function TabDetail(HandlePressKey) {

  // Your HandlePressKeyEnter function
  const callpopup = (event) => 
  {
     HandlePressKey()
  });

  return (
    <div>
      {/* Attach the key press event to this div */}
      <div onKeyDown={callpopup}>
        {/* You can remove the button */}
      </div>
    </div>
  );
}

export default TabDetail;

The problem is, am unable to call the OpenPopUp function in TabBody.js from Tab.js on pressing the + key. The error thrown is: the method OpenPopUp is defined in Tab.js.

Could anyone please suggest ideas to achieve this?

Thank you!

0

There are 0 answers