javascriptreactjsuse-refreact-forwardref

React forwardRef: ref and other props


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?


Solution

  • // 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.