One interesting challenge I encountered recently was passing an open prop to a styled component in order to implement animations for a hamburger icon. Here is the code I used:
const StyledBurger = styled.button`
display: flex;
flex-direction: column;
justify-content: center;
border: 0;
background-color: ${colors.cobaltBlue};
border-radius: 2.7px;
cursor: pointer;
div {
width: 27px;
height: 3px;
margin: 1.5px;
transition: all 0.2s linear;
border-radius: 1.4px;
background-color: ${colors.white};
:first-child {
${({ open }) => open && firstOpenAnimation};
}
:nth-child(2) {
opacity: ${({ open }) => (open ? '0' : '1')};
}
:nth-child(3) {
${({ open }) => open && seconOpenAnimation}
}
}
`;
const firstOpenKeyframe = keyframes`
50% {
transform: translateY(6px) rotate(0);
}
100% {
transform: translateY(6px) rotate(45deg);
}
`;
const secondOpenKeyframe = keyframes`
50% {
transform: translateY(-6px) rotate(0);
}
100% {
transform: translateY(-6px) rotate(-45deg);
}
`;
const firstCloseKeyFrame = keyframes`
50% {
transform:translateY(0) rotate(-45deg);
}
100% {
transform:translateY(-6px) rotate(-45deg) ;
}
`;
const firstOpenAnimation = css`
animation: 0.3s linear ${firstOpenKeyframe} forwards;
`;
const seconOpenAnimation = css`
animation: 0.3s linear ${secondOpenKeyframe} forwards;
`;
const firstCloseAnimation = css`
animation: 0.3s linear ${firstCloseKeyFrame} forwards;
`;
export default StyledBurger;
When the menu is closed, I wanted to reverse the animation that occurred after the first click. I attempted a conditional rendering of animation keyframes based on the open prop, but encountered an issue where the animation was immediately triggered upon page load as it initially evaluated to false. I am currently exploring ways to resolve this and implement the opposite animation when the icon is unclicked. Any suggestions would be greatly appreciated!