gilbarbara / react-floater

Advanced tooltips for React
https://codesandbox.io/s/github/gilbarbara/react-floater/tree/main/demo
MIT License
213 stars 37 forks source link

not positioning correctly if conditionally changes value of target #103

Closed trkas closed 8 months ago

trkas commented 8 months ago

🐛 Bug Report

If I have a Floater with a target and conditionally changes the target value if going into smaller screen, the floater doesn't reposition correctly. if I do a hard refresh on page, it reposition correctly again

To Reproduce

Run this code - using Mui

import { Box, Button, useMediaQuery, useTheme } from "@mui/material";
import Floater from "react-floater";
function App() {
  const theme = useTheme();
  const matchDownSM = useMediaQuery(theme.breakpoints.down("sm"));
  const floater = (
    <Floater
      target={matchDownSM ? "#button" : "#box"}
      autoOpen={true}
      component={<Box sx={{ bgcolor: "yellow" }}>Hello Box</Box>}
    ></Floater>
  );
  return (
    <Box id={"box"}>
      {floater}
      <Button id={"button"}>Hello Button</Button>
    </Box>
  );
}

export default App;

Steps to reproduce the behavior:

Run the code. i have created the app from create-react-app

Expected behavior

When resizing the browser window smaller than "sm" breakpoints, I expected that the floater would anchor at the button, but it doesn't, it stays anchored at the box. But if I refresh the browser, the floater is now under the button.

gilbarbara commented 8 months ago

Hey @trkas Did you try to re-render the whole Floater instead of just the target? Or create a variable target and use it for the target and key props.

trkas commented 8 months ago

Hi, Well the floater re-renders when matchDownSM changes, so that still doesn't work. I can't see what it would help to create a variable target? Can you give example on what you mean?

gilbarbara commented 8 months ago

As stated in the issue template:

Please provide a https://codesandbox.io/ demo or similar.
You can use this template. Issues without a reproduction link are likely to stall.

trkas commented 8 months ago

Hi @gilbarbara - i found a solution by specifying the target as the key property on the Floaters. I am not sure why it works but it does 😁

gilbarbara commented 8 months ago

Hey @trkas

Yeah, that's why I suggested it. You can read more about it in the docs. This library memoizes the target on mount to avoid re-renders. With a different key it's a whole new render.