OverlayTrigger on custom component not working

All we need is an easy explanation of the problem, so here it is.

I’m trying to show a Popover when a custom component (a button) is hovered:

class MyComponent extends React.PureComponent<MyComponentProperties>  {
    public render(): JSX.Element {
        const overlay: JSX.Element = (
            <Popover id={this.uuid}>
                <Popover.Content>
                    Hello world!
                </Popover.Content>
            </Popover>
        );

        return <OverlayTrigger trigger="hover" placement="auto" delay={{show : 700, hide : 0}} overlay={overlay}>
            <MyFancyButton ... />
        </OverlayTrigger >
    }
}
class MyFancyButton extends React.PureComponent<MyFancyButtonProperties> {
    public render(): JSX.Element {
        return <button ...>Hover me!</button>
    }
}

The Popover doesn’t show. However, it works if I change the return of the render function of MyComponent to:

return <OverlayTrigger trigger="hover" placement="auto" delay={{show : 700, hide : 0}} overlay={overlay}>
    <button>Hover me!</button>
</OverlayTrigger >

I checked https://react-bootstrap.github.io/components/overlays/#overlay-trigger and it says:

Note that triggering components must be able to accept a ref since will attempt to add one. You can use forwardRef() for function components.

I’m not sure how to do this. I tried adding a ref property in MyFancyButtonProperties and forwarding it to button, but it doesn’t work:

class MyFancyButton extends React.PureComponent<MyFancyButtonProperties> {
    public render(): JSX.Element {
        return <button ref={this.props.ref} ...>Hover me!</button>
    }
}

My versions:

  • React 16.8.6
  • React bootstrap 1.0.0-beta.14

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I finally found a solution here: https://github.com/react-bootstrap/react-bootstrap/issues/2208#issuecomment-301737531

I modified the render function of MyComponent to

return <OverlayTrigger trigger="hover" placement="auto" delay={{show : 700, hide : 0}} overlay={overlay}>
    <span><MyFancyButton ... /></span>
</OverlayTrigger >

and now it works.

Method 2

Your custom component needs to pass the event handler props through.

const FancyButton = ({ children, ...props }) => (
  <Button {...props}>
    {children}
  </Button>
);

Source: https://github.com/react-bootstrap/react-bootstrap/issues/2208

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply