I have two elements, a reference element, illustrated by a black, rounded button, and a wider component, that resembles a popover, with a pointer. Unlike most popovers on the internet, I decided to go with relative positioning, because I want it to continue occupying the space.
The problem is that, by using react-popper
, it seems like it can't handle the positioning too well. If you take a look at the Sandbox sample below, the arrow is not pointing towards the middle of the rounded button.
The components code, nothing special, just made this to illustrate my big problem. Here's the button, pretty basic.
import { forwardRef } from "react";
export const RoundedBtn = forwardRef(({ children }, ref) => {
return (
<button className="btn" ref={ref}>
{children}
</button>
);
});
And the Popover
import { forwardRef } from "react";
export const Popover = forwardRef(
({ title, footer, popoverProps, children }, ref) => {
const { popperStyles, arrowStyles } = popoverProps;
return (
<div className="popover" ref={ref}>
{title && <header>{title}</header>}
{children}
{footer && <footer>{footer}</footer>}
<span data-popper-arrow style={arrowStyles} className="popover-arrow" />
</div>
);
}
);
Forwarded refs in both components, in Popover I'm using the popper styles to apply it to the arrow (I haven't done so to the Popover container, because it applies position: absolute
to it and I don't want it).
In App.js, again, simple:
export default function App() {
const [refEl, setRefEl] = useState(null);
const [popOverRef, setPopoverRef] = useState(null);
const {
styles: { popper, arrow }
} = usePopper(refEl, popOverRef, {
placement: "top"
});
const popoverProps = {
popperStyles: popper,
arrowStyles: arrow
};
return (
<div className="app example-1">
<RoundedBtn ref={setRefEl}>+</RoundedBtn>
<Popover
popoverProps={popoverProps}
ref={setPopoverRef}
title={title}
footer={footer}
>
{content}
</Popover>
</div>
);
}
Just using usePopper
hook and setting its needed refs.
But, please see this live because it's not aligned correctly. https://codesandbox.io/s/frosty-tess-jtz61e
Can you instruct me what steps to take in order to fix this? It shouldn't matter the technique we use to move the ref and popper elements, we can use align-items: center
(which oddly seems to work fine with the arrow), or align-items: flex-end
, the arrow should still be pointing at the referencing element, or very approximately.
Please help, I would very much appreciate it, it's been driving me insane.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.