I had a styled component that was rendering 3 times, each having a parallax effect.
const ParallaxContainer = styled.section`
position: absolute;
left: 0;
right: 0;
height: 100%;
opacity: 0.3;
bottom: ${props => props.bottomValue}px;
`;
The parallax is achieved by updating the bottom
value every scrollEvent through a pretty expensive calculation. Meaning, this component is getting re-rendered very often.
Unsurprisingly, I was getting the warning Over 200 classes were generated for component styled.section. Consider using the attrs method, together with a style object for frequently changed styles.
So I tried to follow the advice, and refactored the component to this:
const ParallaxContainer = styled.section.attrs(
({ bottomValue }) => ({
style: {
bottom: bottomValue + "px"
}
})
)`
position: absolute;
left: 0;
right: 0;
height: 100%;
opacity: 0.3;
`;
But I am still getting the same error. What am I doing wrong?
Sandbox demonstrating my issue: https://codesandbox.io/embed/styled-components-is-yelling-at-me-attrs-zhnof
The problem is the lines you left commented out in your style. Remember, your style is just a template string. The CSS-style commented lines are only ignored after the string has been interpolated and passed to Styled Components.
The Over 200 classes
error happened in the first place because the style string needed to be re-computed on every scroll event, which results in a completely new styled component instance. Moving it to attrs
is like defining the style in JS in the old-fashioned React way, so these styles don't go through Styled Components.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With