There are many scenarios that we want to call child’s function from it’s parent. This can be done easily with forwardRef and useImperativeHandle.

Let’s define our scenario.
We have a dialog component that could be open by clicking a button, this button is in the parent component.
This is the parent component:

const App = () => {
const [open, setOpen] = useState(false);
return (
<>
<Button
onClick={() => setOpen(true)}
>
Open Dialog
</Button>
<CustomDialog
open={open}
onClose={() => setOpen(false)}
name="React"
/>
</>
);
};

In this code we have open state that controls state of the dialog (show or hide)…

Hamidreza Nazemi

I’m good with JS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store