0

I am using React Popper to position an element relative to another. I have set up some basic code, to provide the starting structure.

export default function App() {
  const [containerRef, setContainerRef] = useState(null);
  const [tooltipRef, setTooltipRef] = useState(null);

  const {
    styles: { popper },
    attributes: { popper: popperAttributes }
  } = usePopper(containerRef, tooltipRef, {
    placement: "bottom-start"
  });

  return (
    <>
      <div className="container" ref={setContainerRef}>
        Content
      </div>
      <span
        ref={setTooltipRef}
        className="tooltip"
        style={{ ...popper }}
        {...popperAttributes}
      >
        Tooltip
      </span>
    </>
  );
}

I have added some styles too, just to see the elements.

.container {
  display: flex;
  align-items: center;
  padding: 0 20px;
  background-color: rgb(255, 121, 121);
  height: 30px;
  border: 1px solid #000;
}

.tooltip {
  width: 100%;
  background-color: #333;
  width: 100%;
  color: #fff;
}

Ok, as you can see, the container has a red-ish background color. What I want though, is, if the tooltip is positioned at the top, I want the container's background to be yellow. Is that possible in React Popper?

Here is the full code. https://codesandbox.io/s/sad-cartwright-r6oyrb

  • Did you check what "usePopper" gives you? There is a "placement" in "state". Just create second css class that is yellow and append it to ".container" if state.placement is top. – Oktay Yuzcan Jul 20 '22 at 14:32
  • @OktayYuzcan I wasn't aware that it's giving a "state" aswell, thank you. Regarding this, would you say it's better (performance-wise) to use state.placement and conditionally give a class to an element, or create a custom modifier? – florinpavel Jul 21 '22 at 13:38

0 Answers0