Bruno
Bruno

Reputation: 19

How to get child component's ref in Hooks

I have a question, if in the Class Component just attach the ref to the child component to get the whole ref, how can the hooks achieve the same result?

Upvotes: 0

Views: 1600

Answers (1)

Gaurav Mithas
Gaurav Mithas

Reputation: 75

Same as in class components, you need to use forwardRef. check the pseudo code below

import {forwardRef} from 'react'
// wrap child component in forwardRef , with ref being a seperate argument to props
const ChildComponent = forwardRef((props, ref) => (
  <Child ref={ref} {...props} />
));

and in parent, just create the ref using useRef hook and pass to child

const ParentComponet =()=>{ 
  const ref = useRef(null)

  return (<ChildComponent ref={ref} {...props}/>)
}

Upvotes: 1

Related Questions