In order to execute a function from a child component, you will need to use Refs. React supports a special attribute that you can attach to any component, that's the ref
attribute, it takes a callback function, and you can access the functions of the child component in the parent accessing this.refs.REF_NAME.METHOD_NAME
.
We are going to create a Parent element, it will render a <Child/>
component. As you can see, the component that will be rendered, you need to add the ref
attribute and provide a name for it. Then, the triggerChildAlert
function, located in the parent class will access the refs property of the this context (when the triggerChildAlert function is triggered will access the child reference and it will has all the functions of the child element).
Now, the child component, as theoretically designed previously, will look like:
The showAlert
method is the only method that will be accesible in this.refs.child
in the parent component.
Example
If you didn't understood well the previous example, you can analyze the following implementation. In this example, we are going to use material-ui and 2 of its components, the drawer and a button. The custom drawer will be located in an extra file Drawer.js:
Nothing special that we need to pay attention, the handleToggle
method is only accesible in the Drawer component, however as we are not going to add any button inside the <Drawer />
component, we need of some way access those methods, otherwise we couldn't use the Drawer. Therefore, in our </Main>
component, we are going to add a simple button that will show the drawer and will access the handleToggle method in the <Drawer />
component:
If you want more information about the ref attribute, read the official documentation in react here. Happy coding !
1 Comment