I'm playing around with React-Bootstrap's OverlayTrigger, which requires the passed child component to be able to receive a ref (stated in the docs: https://react-bootstrap.github.io/components/overlays/#overlaytrigger)
I have the following working code:
const Acomponent = forwardRef((props, ref) => {
return (
<Button {...props} ref={ref}>
{props.children}
</Button>
);
});
const App = () => {
return (
<OverlayTrigger
key="right"
placement="right"
overlay={<Tooltip>Tooltip!!</Tooltip>}
>
<Acomponent>My component with a tooltip</Acomponent>
</OverlayTrigger>
);
};
Is there a way I can use forwardRef inline or as a component in order to avoid all the boilerplate?
Something like:
const App = () => {
return (
<OverlayTrigger
key="right"
placement="right"
overlay={<Tooltip>Tooltip!!</Tooltip>}
>
{
forwardRef((props, ref) => {
<Button {...props} ref={ref}>My component with a tooltip</Button>
}
}
</OverlayTrigger>
);
};
Or:
const App = () => {
return (
<OverlayTrigger
key="right"
placement="right"
overlay={<Tooltip>Tooltip!!</Tooltip>}
>
<ForwardRefWrapper>
<Button>My component with a tooltip</Button>
</ForwardRefWrapper>
</OverlayTrigger>
);
};
In your example, AComponent is just rendering a Button and nothing else, and Button already accepts a ref. If that's the case you have, you should be able to delete AComponent and just do this:
<OverlayTrigger
key="right"
placement="right"
overlay={<Tooltip>Tooltip!!</Tooltip>}
>
<Button>My component with a tooltip</Button>
</OverlayTrigger>
But it's possible you simplified it to ask your question, and AComponent has to do more stuff than just that. In that case: no, there is no shorter option.
Your first example won't work because it will be creating a brand new component type every time App renders. Since the type keeps changing it must unmount and remount each time, wiping out any state in the process.
The second one doesn't work, because ForwardRefWrapper has the same problem that OverlayTrigger has: if you're just given a children prop with an element of a function component, there is no way to know which element inside that function component the ref is supposed to be passed to. No way, unless you write code to do so, which is what forwardRef is for.