Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 582
CSSer Avatar asked Oct 31 '25 09:10

CSSer


1 Answers

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

like image 123
Peter Keuter Avatar answered Nov 01 '25 23:11

Peter Keuter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!