.attrs docs needs clarification
See original GitHub issuehttps://www.styled-components.com/docs/basics#attaching-additional-props
The attrs
function passes all attributes directly to the dom node.
so it should only be used with “safe” values that won’t trigger html incompatibilities.
In the docs the word “props” is being used.
“It allows you to attach additional props (or “attributes”) to a component.”
And it implies that it should be used for organizing the data logic before the css expression. The example actually uses them for something similar to “defaultProps”. If you use it like the docs tells you to you will suddenly generate tons of react warnings.
The docs should be clearer about this function intended behavior to prevent these confusions.
PS:
The behavior that the documentation implies is actually really helpful and the impossibility to use it like this creates the need for workarounds like creating wrapper-components. Would creating a .props
functionality that behaves exactly like attrs
but without the dom printing be something to consider? By creating wrapper components you’re suddenly breaking the styled-components “flow” preventing further “extensions”. With a props
functionality tons of compositions would be possible.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:4
- Comments:10 (3 by maintainers)
Top GitHub Comments
@lifeiscontent @AshCoolman
I came into the same confusion after trying out
.attrs()
but after messing around with it for a while it’s pretty clear what is its purpose and how does it work.Consider this example:
So what happens here is (step by step):
Div
has been used withcolor
prop with valueblue
Div
has a default propcolor
with valuegreen
, but it is overridden by thecolor
prop passed in<Div color="blue" />
defaultProps
) arrive in theattrs
function and get merged with the object passed toattrs
- where what has been passed toattrs
takes precedence (so the valuered
is being taken)div
is going to be rendered withcolor: red
So knowing the above I think we can deduce few hints:
attrs
to specify immutable static propsattrs
to compute other props based on incoming props (passed explicitly or from defaultProps)So replacing
defaultProps
withattrs
makes only sense, when you want the component to ALWAYS have some prop, because doing something like:doesn’t make any sense.
If my description is wrong please correct me @kitten
I’m regrouping some info from 2258. I still see a lot of confusion around
attrs
in the issues.Here is what happens under the hood since
4.1.2