3

A parent component:

const Parent = (props) => {
  const ref = useRef();

  return <Child ref={ref} />
}

and the child:

const Child = forwardRef((props, ref) => {
  return <button ref={ref} ...>click</button>
})

What if I want to pass more props to Child than just ref?

I've searched documents and tutorials, but found nothing; and by trial-and-error, I guess this would work:

// in parent
<Child onClick={...} prop1={...} prop2={...} ref={ref} />

and then in Child, I can get these props (onClick, prop1, prop2) from props.

Is that all I need to do? By putting ref as the last prop passing to the child?

What if I have more than one button in Child that needs a ref?

CSSer
  • 2,131
  • 2
  • 18
  • 37

2 Answers2

3
// in parent
<Child onClick={...} prop1={...} prop2={...} ref={ref} />

The order is irrelevant. forwardRef extracts the ref prop from the properties and creates a wrapper.

The other props are available in props (the first argument in the forwardRef callback-function)

If you want to use multiple refs you can use the example here.

Peter Keuter
  • 778
  • 5
  • 14
3

Well, i had followed this approach,

Parent component

const Parent = (props) => {
  const ref = useRef();

  return <Child _ref={ref} />
}

Child component

const Child = forwardRef(({ _ref, prop1, prop2, prop3, ...props }) => {
  return <button ref={_ref} ...>click</button>
})

And it worked

ezio4df
  • 3,541
  • 6
  • 16
  • 31