How to add functions inside styled-components

Total
60
Shares

i pass the open a prop to the component which is a boolean

i want to add a setTimeout function to hide a component but it shows syntax error

Timeout' is not assignable to parameter of type 
'Interpolation<ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, 
HTMLDivElement>, "key" | keyof HTMLAttributes<HTMLDivElement>> 

here is what i tried

const DrawerContent = styled.div<{ open: boolean; visible?: any }>`
  transition: 0.3s all;
  ${({ open, visible }) =>
    open
      ? css`
          display: flex;
          width: 200px;
          height: 100px;
          background-color: brown;
          position: absolute;
          top: 0;
        `
      : setTimeout(() => { // i want to add this line
          css`
            display: none;
          `;
        }, 200)}
`;

Solution

You can’t get a return value from the setTimeout callback function. If you are trying to hide the node after some time, you should use keyframes:

const hide = keyframes`
    to {
        width:0;
        height:0;
        overflow:hidden;
    }
`;

const DrawerContent = styled.div`
  transition: 0.3s all;
  ${({ open, visible }) =>
    open &&
    css`
      display: flex;
      width: 200px;
      height: 100px;
      background-color: brown;
      position: absolute;
      top: 0;
      animation: ${hide} 0s ease-in 2s forwards;
    `}
`;

Another solution is to move the timeout function outside the DrawerContent component:

const DrawerContent = styled.div`
  transition: 0.3s all;
  ${({ open, visible }) =>
    open &&
    css`
      display: flex;
      width: 200px;
      height: 100px;
      background-color: brown;
      position: absolute;
      top: 0;
    `}
`;

function App () {
  const [show, setShow] = useState(true);

  useEffect(() => {
    let timeout;
    if (show) {
      timeout = setTimeout(() => {
        setShow(false);
      }, 2000);
    }
    return () => clearTimeout(timeout);
  }, [show]);
  return (
    <>
      <div>
        <DrawerContent open={show} visible />
      </div>
    </>
  );
}
Leave a Reply

Your email address will not be published. Required fields are marked *