reactjsreact-bootstrapreact-componentbootstrap-popoverreact-ref

`Popover` (as React component) with `OverlayTrigger`


I'm trying to create rich React component as popover content. If I use example with simple const popover (https://react-bootstrap.netlify.app/components/overlays/#examples-1) everything works fine.

Problem

But custom react component fails to position itself. It appears on top left of the screen enter image description here


const MyPopover = React.forwardRef((props, ref) => {
    return <Popover ref={ref} placement={"bottom"}>
        <Popover.Header as="h3">
            <Form.Control></Form.Control>
        </Popover.Header>
        <Popover.Body>
            <strong>Holy guacamole!</strong> Check this info.
        </Popover.Body>
    </Popover>
})

const PopoverChooser = ({children,  container}) => {
    const _refTarget = useRef(null)

    return <>
          <OverlayTrigger
              trigger="click"
              placement="bottom"
              overlay={<MyPopover ref={_refTarget}/>}
              target={_refTarget.current}
          >
              {children} 
          </OverlayTrigger>
    </>
}
export default PopoverChooser;

As you can see, I'v tried to use ref's, but it's doesn't help.

Question

  1. How can it link popover to target button (in image as dropdown button and in code as {children}).
  2. Or should I position MyPopover manually (by checking button ID and assigning position.. etc.?)
  3. Completely different approach to dig in..?

Solution

  • Your approach to forward the ref was right. What you actually forgot is to also inject props. According to the documentation:

    The and components do not position themselves. Instead the (or ) components, inject ref and style props.

    https://react-bootstrap.netlify.app/components/overlays/#overview

    So what you need to do is to spread the props like this:

    const MyPopover = React.forwardRef((props, ref) => {
      return (
        <Popover ref={ref} {...props}>
    

    https://codesandbox.io/s/trusting-sid-0050g9