0

I have two files named app.js and modal-form.js. When I click the button on the App.js component, I want a function in the modal-form.js file to be triggered. I'm new to the React library and I would appreciate it if you could help me. I hope I could explain.

Example modal-form.js

const [open, setOpen] = React.useState(false);

const handleOpen = () => {
    setOpen(true);
 };

Example App.js

<ModalForm ref={(ref) => this.handleOpen = ref} />

like this.

Gündoğdu Yakıcı
  • 677
  • 2
  • 10
  • 31
  • If the ModalForm component is a child of the App component, short answer is you can't. You have to rethink your design or lever the state up. – AmiralBl3ndic Apr 26 '21 at 13:17
  • Is there a possibility to show a small example? @AmiralBl3ndic – Gündoğdu Yakıcı Apr 26 '21 at 13:18
  • Think of it this way: the only thing a parent can transmit to its children is data or functions via props. You can pass a function as a prop for the child to call when something happens to notify the parent component. When the state of the parent component changes, a render of the children component should occur. – AmiralBl3ndic Apr 26 '21 at 13:20
  • I think this is a big missing. – Gündoğdu Yakıcı Apr 26 '21 at 13:21
  • If your Component 2 is child of your Component 1; inside your Component 1 you can send the function one level down; ` ` If your Component 2 isnt child; but parent of Component 1;then you cannot use this way; maybe rethink your design. There are ways; like write your handleOpen function on the parent component; or use Context and hold your function in context if its a global function; maybe like dark mode etc. And no; its not a big missing feature. Its intentional; called one-directional data flow; you can search for information – Emre A Apr 26 '21 at 13:23

2 Answers2

1

Ideally, No one will recommend this approach but if you still have to implement it that way than you can check following answer for your question. It does explain how to call child component's method from parent.

Call child method from parent

Priyank Kachhela
  • 2,517
  • 8
  • 16
0

I think you are looking for useimperativehandle hook: https://reactjs.org/docs/hooks-reference.html#useimperativehandle

Bart Krakowski
  • 1,655
  • 2
  • 8
  • 25