Default props behavior changed between v3 and v4
See original GitHub issueThe behavior of how defaultProps
are handled has changed between s-c v3 and v4, I’m not exactly sure if this change was intentional but it was not apparent in the changelog, so that’s why I’m filing it 😃.
Anyways, in v3 I could have a Text
component with some default props such as the font. I could then create a Heading
component which is based on Text
but may provide some different default props. In v3, the following example works fine and both the Heading
and Text
components always have a default font
prop. In v4 however, the defaultProps
of the Heading
overwrites all the default props of Text
. If I don’t define any defaultProps
for Heading
it seems to work fine.
const Text = styled.span`
font-family: ${({ font }) => {
if (!font) console.error('FONT PROP NOT FOUND!')
return font
}};
`
Text.defaultProps = {
font: 'sans-serif'
}
const Heading = styled(Text)`
display: block;
font-size: 38px;
`
Heading.defaultProps = {}
Environment
npx envinfo --system --binaries --npmPackages styled-components,babel-plugin-styled-components --markdown --clipboard
N/A, see reproduction.
Reproduction
https://www.webpackbin.com/bins/-KeeZCr0xKfutOfOujxN https://codesandbox.io/s/rkmNRByE4
The exact same demo in two different versions of Styled Components:
s-c v3, Heading
and Text
are both using sans-serif
: https://codesandbox.io/s/6wmwk9l8kk
s-c v4, the font-family
for Heading
is undefined because the font
prop is undefined: https://codesandbox.io/s/9jlw0zq5yo
Steps to reproduce
Expected Behavior
The Heading
component should inherit the defaultProps
from the Text
component like it did in v3. I think in v3 the defaultProps
would be merged?
Actual Behavior
The defaultProps
of Heading
overwrites the defaultProps
of the Text
component even though Heading
is based on the Text
component.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:12 (5 by maintainers)
Top GitHub Comments
Released in v4.3.0
I’ve made a PR to close this issue https://github.com/styled-components/styled-components/pull/2260 and bring back defaultProps folding. I’m still waiting for feedback, but IMO it LGTM.
ps: They are not being defined at built time, even in React. ps2: I was replying to a comment, which got deleted 🤷♂️