Hello Friends đź‘‹,

Welcome To Infinitbility! ❤️

This tutorial will help you to create a ref of your custom functional component in react, after creating ref we are able to use the child component function in the parent component and many things.

Let start today’s tutorial How to create a ref of the functional component in React?

I found, many tutorials where they are explaining how to use ref in functional components but rarely do I find how to make referenceable custom functional components where we can use ref in any place. i.e I’m writing this tutorial. hope it will help you.

Now, let’s create the referenceable functional component, and then we will use it in another functional component.

import { forwardRef, useRef, useImperativeHandle } from "react"

const ChildComp = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    showAlert() {
      alert("Hello from Child Component")
    },
  }))
  return <div></div>
})

function App() {
  const childCompRef = useRef()
  return (
    <div>
      <button onClick={() => childCompRef.current.showAlert()}>Click Me</button>
      <ChildComp ref={childCompRef} />
    </div>
  )
}

export default App

in this above example, we are used to react forwardRef and useImperativeHandle to make things possible. now we will call child component function from parent component using ref.

forwardRef, useImperativeHandle, Example

You can also use the above example in react native, you have to just use react native view, button tags.

Thanks for reading…