Home > Enterprise >  Issue with animation and state
Issue with animation and state

Time:10-18

I'm creating a side menu with navigation which I want to animate sliding. In various tutorials it's pretty simple. Create state and with that controll transform - easy.

So I have my SideNav.tsx component below:

import { Button, Menu } from 'antd';
import React, { useState } from 'react';
import { keyframes } from 'styled-components';
import styled from 'styled-components';
[...]

const SideNav: React.FC = () => {
  const [active, setActive] = useState(false);

  return (
    <Wrapper>
      <MenuWrapper>
        <>
          <AntDMenu
            defaultSelectedKeys={['1']}
            defaultOpenKeys={['sub1']}
            mode='inline'
            theme='dark'
            items={items}
          ></AntDMenu>
          <SideBox />
        </>
      </MenuWrapper>
      <MenuButton
        size='large'
        shape='circle'
        type='primary'
        onClick={() => setActive(!active)}
      >
        {active ? <MenuUnfoldIcon /> : <MenuFoldIcon />}
      </MenuButton>
    </Wrapper>
  );
};

export default SideNav;

const MenuWrapper = styled.div`
  display: flex;
  position: fixed;
  left: 0;
  top: 0;
  width: 160px;
  height: 100%;
  transition: transform 300ms;
  transform: ${(active) => (active ? 'translateX(0%)' : 'translateX(-100%)')}; //<---- There is a main problem
`;

const Wrapper = styled.div`
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
`;

const AntDMenu = styled(Menu)`
  padding-top: 100%;
`;

const MenuButton = styled(Button)`
  margin-top: 16px;
  margin-left: 16px;
  border: 1px;
  position: fixed;
  left: 0;
  top: 0;
  :hover {
    transform: scale(1.2, 1.2);
    cursor: pointer;
  }
`;

So it should hide my SideNavigation to the left over screen. But nothing happends with menu, only icon on button is changing.

CodePudding user response:

You forgot to add active prop to your component.

<MenuWrapper active={active}>

Then in your styled component definition:

const MenuWrapper = styled.div`
  display: flex;
  position: fixed;
  left: 0;
  top: 0;
  width: 160px;
  height: 100%;
  transition: transform 300ms;
  transform: ${(props) => (props.active ? 'translateX(0%)' : 'translateX(-100%)')}; //<---- There is a main problem
`;
  • Related