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?
// 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With