Styled component not transforming on prop change
See original GitHub issueHi,
Having a problem with a side drawer component that is supposed to slide in from the right on open. Wrote it in a separate CSS file first and it works like a charm, but for some reason styled-components ignores the fact that the props.open changes. I tried logging the props and the component receives it as it should.
Here is my code:
const SideDrawerBox = styled.div
position: fixed;
width: 280px;
max-width: 70%;
height: 100%;
right: 0;
top: 0;
z-index: 200;
background-color: #2E2E3A;
padding: 32px 16px;
box-sizing: border-box;
transition: transform 0.3s ease-out;
transform: translateX(${props => props.open ? '0%' : '+100%' });
@media(min-width:1024px){
display: none;
}
``
<SideDrawerBox> <SideDrawerItems> <SideDrawerLogo src={Logo} /> <SideDrawerText>Register</SideDrawerText> <SideDrawerText>Log in</SideDrawerText> </SideDrawerItems> </SideDrawerBox>
Any ideas? Thanks!
Issue Analytics
- State:
- Created 6 years ago
- Comments:7 (3 by maintainers)
You’re recreating the styled component
SideDrawerBox
over and over again on every render. This will cause React to recycle that part of your element tree and readd everything again.Very expensive for all moving parts that are involved 😉
You’ll always want to have every component, including especially styled components, outside of other component’s render cycle, or any other method 😄
@bailycase as stated above, the StyledComponent is recreated every time the parent component renders. Like any component this will cause React not to recycle the underlying DOM structure, which will mean that no animation actually plays since the DOM node is destroyed.
We create actual components so they’ll have to be kept static across the life cycle of a component.
If you’re still experiencing issues and need help though it might make sense to open a new issue and ask for help with your specific snippet of code 🙌