1

I want a component to perform the slide animation to the right when it is mounted, and to the left when it is unmounted, all using the div belonging to the "profile-slide-container" class as the container of the Slide component, but I have no idea how to do it.

Here is the code:

function Main(){
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  return(
    <div className="main">
      <Header />
      <div className="profile-slide-container">
      {showProfileMenu && <Slide in={true} direction={"right"}><div className="pseudo-left-section"><ProfileMenu onClick={() => setShowProfileMenu(false)} /></div></Slide>}
      </div>
      <div className="left-section">
            <div>
              <LeftSectionHeader onClick={() => setShowProfileMenu(true)} />
              <LangMenu />
            </div>
        </div>
      </div>
  );
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Gigi Carti
  • 53
  • 8

1 Answers1

2

Below is the correct code to move the item in and out of the container. You need to create a ref that holds a reference of the container element and pass it to the Slide component via the container prop. When a container is provided, Slide gets its bounding rectangle, then calculate the distance to translate outside of the container border.

You may also want to set overlow: 'hidden' in the container so the animated item can disappear when it moves outside of the container.

const [checked, setChecked] = React.useState(false);
const containerRef = React.useRef(null);
const handleChange = () => setChecked((prev) => !prev);

return (
  <Box sx={{ width: `calc(100px + 16px)` }}>
    <FormControlLabel
      control={<Switch checked={checked} onChange={handleChange} />}
      label="Show"
    />
    <Box
      ref={containerRef}
      style={{
        marginLeft: 130,
        backgroundColor: 'gray',
        width: 400,
        height: 200,
        overflow: 'hidden',
      }}
    >
      <Slide direction="right" in={checked} container={containerRef.current}>
        <Box sx={{ width: 50, height: 50, bgcolor: 'pink' }} />
      </Slide>
    </Box>
  </Box>
);

Codesandbox Demo

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230